I cannot get this CORS workaround to work in Chrome 52.0. My iframe and parent page are on different subdomains.
My iframe's event listener:
window.onload = function () {
window.addEventListener("message", function(event) {
//doesn't log it
console.log('message');
if(event.data === "invokeChildFunction()") {
childFunction();
}
});
function childFunction() {
alert('Parent frame just invoked my function')
}
}
The parent frame:
var iframeWindow = $('iframe').contentWindow;
var invokeChildFunction = function () {
iframeWindow.postMessage("invokeChildFunction()", "https://mansion-assessment-sdimoff.c9users.io/CORS/index.html");
}
invokeChildFunction()
doesn't log anything at the iframe's page
postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
PostMessage() is a global method that safely enables cross-origin communication. It's a lot like Ajax but with cross-domain capability. We'll give it a whirl by setting up two-way communication between a web page and an iframe whose content resides on another server.
Sending some data from the child iframe to the parent window is also pretty simple. Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.
You should try using
In parent frame:
var iframe = $('iframe')[0];
iframe.contentWindow.postMessage('invokeChildFunction', iframe.contentWindow.location);
In child/iframe:
window.addEventListener('message', function (event) {
if (event.data === 'invokeChildFunction') {
// do whatever you want to
}
})
What you did wrong was selecting elements with tag-name, on selecting elements with tag name you get an array of elements so you need to reference them as array.
Also use some validation to validate the source of events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With