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

Member

by ryleigh , in category: HTML & CSS , 7 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 7 months 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.

Related Threads:

How to check iframe is loaded in javascript?
How to pause video on iframe when page is loaded?
How to add iframe with javascript to ajax loaded content?
How to call a javascript function from within iframe?
How to call a javascript function when iframe finished loading?
How to run javascript on an iframe page?