postMessage in HTML5 to send messages between windows and iframes
Join the DZone community and get the full member experience.
Join For Freeever had the need to communicate between windows or the current window and an inner iframe? across domains as well? i bet you have, but now we have a nice option for doing that!
the solution is called postmessage and is part of the html5 web messaging specification . what makes it cool, and very easy to use, is that all you need to trigger it is to call a method and add an event handler:
- call the postmessage method of the window/iframe element you want to send the information to.
- specify origin. should be a domain or a wildcard "*"
- in the receiving window, just add an event listener for the message event.
-
optional: add an origin check for security reasons.
the code to do this
in this example we will have one containing page with a form, posting a message to an iframe in that page.
code used in the containing page
<form id="the-form" action="/"> <input type="text" id="my-message" value="your message"> <input type="submit" value="postmessage"> </form> <iframe id="da-iframe" src="postmessagetarget.html"></iframe>
window.onload = function () { var iframewin = document.getelementbyid("da-iframe").contentwindow, form = document.getelementbyid("the-form"), mymessage = document.getelementbyid("my-message"); mymessage.select(); form.onsubmit = function () { iframewin.postmessage(mymessage.value, "http://robertnyman.com"); return false; }; };
code used in the iframe
<p id="received-message">i've heard nothing yet</p>
function displaymessage (evt) { var message; if (evt.origin !== "http://robertnyman.com") { message = "you are not worthy"; } else { message = "i got " + evt.data + " from " + evt.origin; } document.getelementbyid("received-message").innerhtml = message; } if (window.addeventlistener) { // for standards-compliant web browsers window.addeventlistener("message", displaymessage, false); } else { window.attachevent("onmessage", displaymessage); }
web browser support
the nice thing is that this is supported in:
- internet explorer 8.0+
- firefox 3.0+
- safari 4.0+
- google chrome 1.0+
-
opera 9.5+
demo and my html5 playground
you can see the above code in action at my postmessage demo , which is part of a new testing ground on my web site, html5 – information and samples for html5 and related apis which displays various html5 examples, the code to run them and web browser compatibility..
play around and enjoy!
Opinions expressed by DZone contributors are their own.
Trending
-
Using OpenAI Embeddings Search With SingleStoreDB
-
Database Integration Tests With Spring Boot and Testcontainers
-
Essential Architecture Framework: In the World of Overengineering, Being Essential Is the Answer
-
What Is Envoy Proxy?
Comments