Chrome扩展程序将消息从iFrame发送到事件页面,然后再发送到内容脚本
我从内容脚本中插入了iframe.它工作正常.但是,如果要在iframe上显示父级的html内容,则必须使用消息传递在iframe和内容脚本之间进行通信,但这是行不通的.然后,我尝试将消息从iframe发送到事件页面",然后发送到内容脚本".内容脚本收到消息后,将查询html内容并回复.它也不起作用.我该如何运作?
I have inserted an iframe from content script. It works fine. But if I want to display parent's html content on iframe, I have to use messaging to communicate between iframe and content script, but it doesn't work. Then I tries to send message from iframe to "event page" then to "content script". Once content script receives the message, it will query the html content and reply. It doesn't work either. How can I make it work?
内容脚本:
var iframe = document.createElement('iframe');
iframe.id = "popup";
iframe.src = chrome.runtime.getURL('frame.html');
document.body.appendChild(iframe);
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.from === 'event' && msg.method == 'ping') {
sendResponse({ data: 'pong' });
}
});
事件页面:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.from === 'popup' && msg.method === 'ping') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
from: 'event',
method:'ping'}, function(response) {
sendResponse(response.data);
});
});
}
});
frame.js
// This callback function is never called, so no response is returned.
// But I can see message's sent successfully to event page from logs.
chrome.runtime.sendMessage({from: 'popup', method:'ping'},
function(response) {
$timeout(function(){
$scope.welcomeMsg = response;
}, 0);
});
我找到了一个相关问题. https://stackoverflow.com/a/20077854/772481
I found a related question. https://stackoverflow.com/a/20077854/772481
从chrome.runtime.onMessage.addListener文档中:
From the documentation for chrome.runtime.onMessage.addListener:
事件侦听器返回时,此函数将变为无效,除非您从事件侦听器返回true表示您希望异步发送响应(这将使消息通道向另一端开放,直到调用sendResponse为止).
This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).
所以我必须返回true来指示sendResponse是异步的.
So I have to return true to indicate the sendResponse is async.
事件页面:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.from === 'popup' && msg.method === 'ping') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
from: 'event',
method:'ping'}, function(response) {
sendResponse(response.data);
});
});
return true; // <-- Indicate that sendResponse will be async
}
});