How to invoke a function in iframe using javascript?

Member

by kadin , in category: Javascript , 13 days ago

How to invoke a function in iframe using javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 13 days ago

@kadin 

To invoke a function in an iframe using JavaScript, you can access the content window of the iframe and then call the function from the parent window. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
  <title>Invoke Function in Iframe</title>
</head>
<body>
  <iframe id="myIframe" src="iframe.html"></iframe>

  <script>
    var iframe = document.getElementById('myIframe');
    var iframeWindow = iframe.contentWindow;

    function invokeFunctionInIframe() {
      iframeWindow.myFunction();
    }
  </script>
</body>
</html>


In the above example, we have an iframe with the ID myIframe that loads a separate HTML file iframe.html. We then grab a reference to the iframe's content window using iframe.contentWindow. The invokeFunctionInIframe function is then called from the parent window to call the myFunction function inside the iframe.


In the iframe.html file, you can define the myFunction function as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
  <title>Iframe HTML</title>
</head>
<body>
  <script>
    function myFunction() {
      console.log('Function invoked from parent window');
    }
  </script>
</body>
</html>


When the invokeFunctionInIframe function is called from the parent window, it will print 'Function invoked from parent window' in the console, indicating that the function in the iframe was successfully invoked.