How to call javascript when specific page is loaded into an iframe?

Member

by ryleigh , in category: HTML & CSS , 17 days ago

How to call javascript when specific page is loaded into an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 16 days ago

@ryleigh 

To call JavaScript when a specific page is loaded into an iframe, you can use the following approach:

  1. Add an onload event listener to the iframe element in the parent HTML document.
1
<iframe id="myFrame" src="page.html" onload="myFunction()"></iframe>


  1. Define the myFunction JavaScript function in the parent HTML document, which will be called when the iframe content is loaded.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function myFunction() {
  // Get the iframe element
  var iframe = document.getElementById("myFrame");

  // Get the document of the iframe
  var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
  
  // Call the JavaScript function in the iframe document
  iframeDoc.myFunctionInIframe();
}


  1. In the page that is loaded into the iframe (page.html in this example), define the myFunctionInIframe JavaScript function that you want to call when the iframe content is loaded.
1
2
3
function myFunctionInIframe() {
  alert('JavaScript function called in iframe!');
}


By following these steps, you can call a JavaScript function in the iframe content when the specific page is loaded into the iframe.