如何從 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.