从C++调用javascript函数

Calling a javascript function from C++

本文关键字:函数 javascript 调用 C++      更新时间:2023-10-16

我想从C++代码中调用一个Javascript函数。

以下是我的Javascript代码(hello.html)

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction() {
    alert("hello");
}
document.getElementById("demo").innerHTML = myFunction(); 
</script>
</body>
</html>

假设我有如下的C++代码

#include<iostream>
using namespace std;
int main()
{
 // Calling the Javascript function  [ myFunction() ] here 
}

我有一个运行Ubuntu 10.04的网关设备,我不能在设备上安装任何新软件。

我尝试使用nodejs和emscriptem从C++调用javascript函数。使用nodejs和emscriptem方法我需要在网关设备上进行apt-get更新、安装SDK等操作,这是不允许的。

那么,除了nodejs和emscriptem之外,还有其他方法可以从C++中调用javascript函数吗?

考虑到您的局限性,您可以用C++编写一个相当复杂的服务器软件,并附带JavaScript,该软件将在打开的浏览器窗口中运行,并轮询服务器上的套接字(即您的C++程序)。

或者,实现这一点的一种非常简单但相当丑陋的方法是通过C++中的system函数调用浏览器,在执行时运行脚本,例如

#include <stdlib.h>

int main(int argc, char argv[])
{
    // Code to retrieve database results
    // Code to generate HTML/JavaScript file - if relevant - saving to /path/script.html
    // Run the browser with your script loaded
    system("firefox -browser -url /path/script.html");
    return 0;
}

我有一种方法可以将C++代码与同一机器中的页面通信没有系统调用,没有外部库。只是标准的javascript和C++诀窍是C++代码生成一个调用函数的js,然后页面定期加载js来运行函数。

C++代码

#include <fstream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
int call_id = 0;
//the function that commit an update
void callFunction() {
  // the file to write the response
  ofstream fout("response.js");
  //this file just call javascript function with a correlative
  //see the page for the definition of caller function
  fout << "caller(" << call_id++ << ", myFunction);"; 
}
int main(int argc, char** argv) {
  //a dummy loop to generate different updates
  while ( true ) {
    sleep(2);
    if ( std::rand()%2 )
      callFunction();
  };
}

页面

<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="application/javascript">
//this code is needed to prevent repeated calls. It checks a correlative to each function call to not repeat it
var call_id = 0;
function caller(i, func) {
  if ( call_id < i ) {
   call_id = i;
   func();
  }
}
//your function
function myFunction() {
  alert("my Function called");
 }
//this code load an js script and prevents infinite spamming of script elements
function loadScript(file) {
  var id = "some_script_id";
  var e = document.getElementById(id);
  if ( e != null )
    e.parentNode.removeChild(e);
  var script = document.createElement("script");
  script.id = id;
  script.src = file;
  document.body.appendChild(script);
}
//to update
window.setInterval(function(){
  //replace with the path where the c++ code write the response 
  loadScript("file:///path/to/response.js"); 
}, 1000);
</script>
</body>
</html>