I try to send message from an iframe loaded from my extension to my extension (background script or content script). The created Iframe is loaded from the extension via a content script. I am searching for a way to communicate but all my attempts failed...
Manifest.json
{
"author": "***********",
"background": {
"page": "back/background.html",
"persistent": true
},
"browser_action": {
"default_title": "***",
"default_popup": "./popup/popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["./content/allurls.js"],
"all_frames":true
},
{
"matches": ["<all_urls>"],
"js": ["./banner/confirm_banner.js"]
}
],
"web_accessible_resources": [
"frame.html"
],
"description": "oui",
"manifest_version": 2,
"name": "***",
"permissions": ["tabs"],
"version": "1.0"
}
Confirm_banner.js (load the iframe)
var extensionOrigin = 'chrome-extension://' + chrome.runtime.id;
window.onload = load_iframe();
function load_iframe()
{
if (!location.ancestorOrigins.contains(extensionOrigin))
{
var iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL('../frame.html');
iframe.style.cssText = 'position:fixed;top:0;left:0;display:block;' +
'width:100%;height:40px;';
document.body.appendChild(iframe);
}
}
Frame.js (script linked with frame.html)
$(document).ready(function()
{
$('#jamais').click(function()
{
send_message("BANNER", "jamais");
alert("send");
});
});
function send_message(type, data)
{
var msg = {
type: type,
data: data
};
window.postMessage(msg, "*");
}
Handler in allurls.js (content script)
window.addEventListener('message', function(event) {
if (event.data.type && (event.data.type === 'BANNER'))
{
alert("ouimonsieur");
}
});
So the message from iframe.js is well sent (prooved by the alert) but the content script recieve nothing from it, even before the :
if (event.data.type && (event.data.type === 'BANNER'))
Can someone see what is wrong or what other message passing protocol i can use (i also tried with top.window.postmessage) ?
Ty wOxxOm for the answer, i was close :
just replace window
by parent
in frame.js
and all works perfectly.
Because even if the content script run in iframe,
Frame.js
is not a content script, it's a iframe script and runs in the context of the extension.
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