Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีเรียกฟังก์ชัน JavaScript จาก C++

เพื่อเรียกฟังก์ชัน JavaScript จาก C++ ให้สร้างไฟล์ .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"); 
      } 
      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>