Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách gọi hàm JavaScript từ C++

Để gọi hàm JavaScript từ C++, hãy sinh ra một file .js gọi hàm đó. Trang web sẽ load file JS và hàm chạy.

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

HTML

<html>
  <body>
    <script>
      var callId = 0;
      function caller(i, func) {
        if (callId < i) {
          callId = i;
          func();
        }
      }
      function display() {
        alert("my Function called");
      }
      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() {
        loadScript("file:///path/generate.js");
      }, 2000);
    </script>
  </body>
</html>

Lưu ý: Cách này khá cũ và phức tạp. Hiện nay thường dùng WebAssembly, Node.js addons, hoặc Electron/IPC để giao tiếp C++ ↔ JavaScript hiệu quả hơn.