How to call a javascript function from within iframe?

Member

by lew , in category: Javascript , 11 days ago

How to call a javascript function from within iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 10 days ago

@lew 

To call a JavaScript function from within an iframe, you can use the contentWindow property of the iframe element to access the window object of the iframe's content. Here's an example of how to do this:

  1. First, give your iframe element an id so you can easily reference it:
1
<iframe id="myIframe" src="path/to/iframe-content.html"></iframe>


  1. Next, access the iframe element and its contentWindow property to call a function within the iframe:
1
2
3
4
5
6
7
8
// Get the iframe element
var iframe = document.getElementById("myIframe");

// Access the window object of the iframe's content
var iframeWindow = iframe.contentWindow;

// Call a function within the iframe
iframeWindow.myFunction();


In this example, myFunction is a JavaScript function defined within the content of the iframe. By using the contentWindow property of the iframe element, you can access the window object of the iframe's content and call any function defined within it.


Make sure that the iframe content and the parent document are hosted on the same domain to avoid cross-origin security restrictions.