Iframe relationship using postMessage

I have a parent page for domain A ( http://example.com )

There are two frames on the parent page that are the same domain, but are not A. ( http://test.com )

Is there a way to pass a value from one iframe test.com to another when the parent is example.com, or is it the behavior that I describe against the iframes `` rules ''

thanks

+6
source share
1 answer

Checkout JSFiddle , I modeled cross-domain iFrames to make it more readable. Basically, the main parent of both frames acts as an intermediary for resending the message to the target frame, but the frames trigger all actions and responses.

HTML

<!-- Adding the sandboxing attribute to illustrade cross-domain --> <iframe id="one" sandbox="allow-scripts"></iframe> <iframe id="two" sandbox="allow-scripts"></iframe> 

Javascript

 var frame_one = document.getElementById('one'); var frame_two = document.getElementById('two'); // The parent has to mediate because cross-domain sandboxing // is enabled when on different domains, plus backwards compatible. window.addEventListener('message', function (m) { // Using an object with a 'frame' property that maps to the ID // which could be done as you would like. var targetFrame = document.getElementById(m.data.frame); targetFrame.contentWindow.postMessage(m.data.message, '*'); }, false); /** * This is just to illustrate what a normal document would look * like you should just set the normal 'src' attribute and the * string would be the normal HTML of the documents. */ frame_two.srcdoc = '<!DOCTYPE html>\ <html>\ <head>\ <script>\ window.addEventListener("message", function (m) {\ alert("Frame Two Says: " + m.data);\ }, false);\ window.addEventListener("load", function () {\ window.parent.postMessage({frame: "one", message: "Received message from frame two!"}, "*");\ }, false);\ </script>\ </head>\ <body>\ two\ </body>'; frame_one.srcdoc = '<!DOCTYPE html>\ <html>\ <head>\ <script>\ window.addEventListener("message", function (m) {\ alert("Frame One Says: " + m.data);\ }, false);\ window.addEventListener("load", function () {\ setTimeout(function () {\ window.parent.postMessage({frame: "two", message: "Received message from frame one!"}, "*");\ }, 1500);\ }, false);\ </script>\ </head>\ <body>\ one\ </body>'; 
+7
source

All Articles