Answer the question
In order to leave comments, you need to log in
Why might window.postMessage not work?
Hello.
Faced a task where it was necessary to link a frame and a window on different domains, the only solution was to use window.postMessage.
For some reason it doesn't want to work.
Everything works correctly in my browser, but others do not
I have
Windows 10 Chrome
Others
MacOS Safari
MacOS Chrome
Windows 10 Chrome
Window
function customHandler(callback){
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener ("message", callback, false);
} else {
if (window.attachEvent) { // IE before version 9
window.attachEvent("onmessage", callback);
}
}
}
customHandler(function(e) {
console.log('WINDOW1: recv: ', e.data);
if (e.data.status == true) {
var data = {status: false, message: 'test'};
console.log('WINDOW1: send: ', data);
document.getElementById('regpopFrame').contentWindow.postMessage(data, "*");
}
});
$(window).on('message', function(e) {
console.log('WINDOW2: recv: ', e.originalEvent.data);
if (e.originalEvent.data.status == true) {
var data = {status: false, message: 'test'};
console.log('WINDOW2: send: ', data);
document.getElementById('regpopFrame').contentWindow.postMessage(data, "*");
}
});
window.onmessage = function(e) {
console.log('WINDOW3: recv: ', e.data);
if (e.data.status == true) {
var data = {status: false, message: 'test'};
console.log('WINDOW3: send: ', data);
document.getElementById('regpopFrame').contentWindow.postMessage(data, "*");
}
};
function customHandler(callback){
if (window.addEventListener) { // all browsers except IE before version 9
window.addEventListener ("message", callback, false);
} else {
if (window.attachEvent) { // IE before version 9
window.attachEvent("onmessage", callback);
}
}
}
customHandler(function(e) {
console.log('FRAME1: recv: ', e.data);
if (e.data.status == true) {
var data = {status: true, message: 'test'};
console.log('FRAME1: send: ', data);
parent.postMessage(data, "*");
}
});
$(window).on('message', function(e) {
console.log('FRAME2: recv: ', e.originalEvent.data);
if (e.originalEvent.data.status == true) {
var data = {status: true, message: 'test'};
console.log('FRAME2: send: ', data);
parent.postMessage(data, "*");
}
});
window.onmessage = function(e) {
console.log('FRAME3: recv: ', e.data);
if (e.data.status == true) {
var data = {status: true, message: 'test'};
console.log('FRAME3: send: ', data);
parent.postMessage(data, "*");
}
};
$(window).load(function(){
parent.postMessage({status: true, message: 'test'}, '*');
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question