3

I have iframe loaded on a web page. Is it possible to call function in an iframe of parent webpage from extension ?

have done all-frames:true in manifest.json

iframe.html as follows:

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

content.js as follows:

/* 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);
});
P. Frank
  • 5,691
  • 6
  • 22
  • 50
  • Possible duplicate of [Call parent Javascript function from inside an iframe](http://stackoverflow.com/questions/6929975/call-parent-javascript-function-from-inside-an-iframe) – CBroe Jan 20 '16 at 13:14

1 Answers1

0

you can try with this:

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>

background.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..."});
     
    });     
}});

You can also check the Chrome documentation, here you will find more implementations https://developer.chrome.com/apps/messaging#connect

I hope it helps

Frank Jose
  • 346
  • 3
  • 3