繁体   English   中英

是否可以从扩展调用父网页的 iframe 中的函数

[英]Is it possible to call function in an iframe of parent webpage from extension

我在网页上加载了 iframe。 是否可以从扩展调用父网页的 iframe 中的函数?

已经在 manifest.json 中完成了 all-frames:true

iframe.html如下:

<body>
    <div class="row">                       
        <button type="button" class="btn btn-primary" id="manual-dial" onclick="dial()";>DIAL</button>
    </div>
</body>

content.js如下:

/* cnt access frame id */
chrome.runtime.sendMessage(window.parent.frames[1].document.id);
window.parent.frames[1].document.id.onload = function() {
    // want to call dial() of iframe
    chrome.runtime.sendMessage("this is my response");
}

background.js

chrome.runtime.onMessage.addListener(function(response,sender,sendResponse)   {
    alert(response);
});

你可以试试这个:

iframe.html

<body> 
   <div class="row"> 
    <button type="button" class="btn btn-primary" id="manual-dial" onclick="dial()";>DIAL</button>
   </div> 
</body> 

<script type="text/javascript"> 
   function dial(){ 
      var portName = "dialPort" 
      var port = chrome.runtime.connect({name: portName}); 
      
      //this postMessage is just to stimulate the listener in the background.js 
      port.postMessage({any: "anyThing"});

      // You can recive the reponse 
      port.onMessage.addListener(function(msg) {
           /** Here you can exec any function **/ 
      });

</script>

背景.js

chrome.runtime.onConnect.addListener(function(port) {

if(port.name == "dialPort"){

    port.onMessage.addListener(function(msg) {
        /**
          Here you can exec any function 
        **/

        //And also, you can send the response to the iframe
        port.postMessage({response: "Any Thing..."});
     
    });     
}});

您还可以查看 Chrome 文档,在这里您会找到更多实现https://developer.chrome.com/apps/messaging#connect

我希望它有帮助😃

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM