Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
Html Window: subscribe to the message events of an iframe window element

I know the basic usage of postMessage https://developer.mozilla.org/fr/docs/Web/API/Window/postMessage when you want to send data to the parent window from an iframe. But is it possible to make this more generic? for example, if in my iframe I publish with postMessage on the window object of my iframe, what could prevent the main window to add an event listener on the messages of the iframe. Here is an example :

in a directory tree that look like this:

root
  |___ frontpage
  |        |____index.html
  |___ iframe
           |____index.html

the iframe/index.html

<!DOCTYPE html>
<html>
  <head>
    <title>iframe</title>
    <meta charset="utf-8" />
    <script>
      const trustedOrigins = ["http://localhost:5001"];

      function sendMsg(msg) {
        console.log(`Send message iframe window`, msg);
        window.postMessage(msg, trustedOrigins[0]);
      }
       setInterval(() => { sendMsg("Coucou") }, 5000);
    </script>
  </head>
  <body>
    <h1>Iframe body</h1>
  </body>
</html>

the main page that embed the iframe : frontpage/index.html

<!DOCTYPE html>
<html>
  <head>
    <title>main</title>
  </head>
  <body>
    <iframe src="http://localhost:5001/index.html"></iframe>

    <script>
      const trustedOrigins = ["http://localhost:5001"];

      function onMsg(msg) {
        console.log(`Message from an iframe`, msg);
      }

      const iframe = document.querySelector("iframe");
      iframe.onload = () => {
        console.log('Adding event listener on the iframe to catch its messages');
        iframe.contentWindow.addEventListener("message", onMsg, false);
      };

    </script>
  </body>
</html>

I expected to be able to display the messages that the iframe send to itself be nothing is displayed

install http-server to test it npm install -g http-server

cd frontpage
http-server -p 5000
cd iframe
http-server -p 5001

go with a browser to http://localhost:5000 and look at the console messages, the iframe send its messages but the event listener catch any of it.

Why ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

window.addEventListener("message", function(event) { console.log(event); }, false);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!