如何从 C++ 调用 JavaScript 函数?


要从 C++ 中调用一个 JavaScript 函数,请生成一个 js 文件,其中调用函数。网页将加载 JS,函数将运行 -

int callId = 0;
void callFunction() {
   // the js file
   ofstream fout("generate.js");
   fout << "caller(" << callId ++ << ", display);";
}
// code

HTML

<html>
   <body>
      <script>
         var callId = 0;
         function caller(i, func) {
            if (callId < i ) {
               callId = i;
               func();
            }
         }    
         function display() {
            alert("my Function called");
         }
         // load js script
         function loadScript(file) {
            var myId = "gh";
            var e = document.getElementById(myId);
            if ( e != null )
            e.parentNode.removeChild(e);
            var script = document.createElement("script");
            script.myId = myId;
            script.src = file;
            document.body.appendChild(script);
         }
         window.setInterval(function() {
            //path to the js file
            loadScript("file:///path/generate.js");
         }, 2000);
      </script>
   </body>
</html>

更新于: 10-2-2020

878 浏览量

开启你的 事业

完成课程,获得认证

开始
广告
© . All rights reserved.