I'm developing a Google Chrome Extension that injects a script on a webpage, gather some data from the web page, call an iframe and send that data to the iframe. Since this process needs to be cross-domain, postMessage was the only thing i could think of for implementing this however i'm not able to receive this data in iframe.
(Btw, is there any other method by which i can achieve same functionality?)
Below is my script that i inject on a webpage when a user clicks on the extension.
jQuery('body').append('<div style="height: 100% !important; width: 100% !important; position: fixed !important; margin: 0% auto !important; background: rgba(17, 17, 17, 0.9) !important; left: 0 !important; right: 0 !important; z-index: 99999999 !important; top: 0% !important;" id="image-grabber-container"><iframe id="vwframe" src="https://example.com/abcd.php" frameborder="0" style="display: block !important; position: fixed !important; height: 100% !important; width: 100% !important; top: 0px !important; left: 0px !important; bottom: 0px !important; right: 0px !important; margin: 0px !important; clip: auto !important; z-index: 7147483657 !important;"></iframe></div>');
setTimeout(function(){
var dTitle = document.title;
var receiver = document.getElementById('vwframe').contentWindow;
receiver.postMessage(dTitle, '*');
},1000);
I've used setTimeout
here just to make sure that iframe is available/loaded when i post message.
Now, i call a script in the iframe to receive the message:
window.onload = function() {
function receiveMessage1(e) {
console.log('mSG');
if (e.origin !== currentUrl)
return;
parentTitle = e.data;
console.log(parentTitle);
}
if (window.addEventListener){
console.log('if');
window.addEventListener("message", receiveMessage1, false);
console.log('if end');
} else {
console.log('else');
attachEvent("onmessage", receiveMessage1);
console.log('else end');
}
}
I see no error in console however receiveMessage1
function fails to work. What could be the possible reason for this?
P.S. I was able to send message from iframe to parent but not vice versa.