2

I have an html file named first.html which has an iframe element to load another html file named second.html. How can we communicate between these two html files. I have tried to trigger an event from the second.html and to catch the same on first.html. But event propagation is not successful.

Here is the first.html file

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" /> 
<script>
   function onLoad(){
      alert("onLoad");
      var iframe = $('#iframeID').contents();
      iframe.find("#button").on("SUBMIT",function(){
          // business logic
          alert("Clicked");
      });
   }
</script>
</head>
<body>
   <iframe id="iframeID" onload="onLoad()" height="1000" width="1000" src = './second.html'></iframe>
</body>
</html>

Here is the second.html file

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" />
    <script>
        function myFunction(){
            $('#button').trigger("SUBMIT");
        };
    </script>
</head>
<body>
    <button id="button" type="button" onclick="myFunction()">Click me</button>
</body>
</html>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Naveen Kumar H S
  • 1,304
  • 16
  • 30

1 Answers1

1

You can't use jquery to communicate , Because Event bubbling stops at root of the document and that is iframe container and doesn't reach host document. You can use the Post message to communicate.

Try this code it's works .

Here is the first.html file.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>

 // addEventListener support for IE8
        function bindEvent(element, eventName, eventHandler) {
            if (element.addEventListener){
                element.addEventListener(eventName, eventHandler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + eventName, eventHandler);
            }
        }

 // Listen to message from child window
        bindEvent(window, 'message', function (e) {
           alert("Got the message from child");
        });
</script>
<body>
   <iframe   name="iframeID"   height="1000" width="1000" src = './second.html'></iframe>
</body>
</html>

second.html

<!DOCTYPE html>
<html>
<body>
  <head>

<button id="button" type="button" onclick="myFunction()">Click me</button>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"/>
 <script>

    function myFunction(){
    var message = 'Send the message to parent ';
       window.parent.postMessage(message, '*');
     };

 </script>
 </body>
</html>
Harish CHH
  • 104
  • 11