我正在查看嵌入了iframe的网页。我需要从网页和所有嵌入式iframe的扩展浏览器操作中收集信息。我有以下代码:如何从iframe中的内容脚本传递消息?
清单
{
"manifest_version": 2,
...
"content_scripts": [
{
"all_frames": true,
"js": [ "contentscript.js" ],
"matches": [ "http://*/*", "https://*/*", "file:///*" ],
"run_at": "document_start"
}
],
...
}
浏览器操作弹出
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id,{command: 'collectPageDetails'},function (details) {
console.log('got details');
});
});
内容脚本
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.command === 'collectPageDetails') {
console.log('getting page details');
sendResponse({ details: 'something' });
return true;
}
});
我在这里看到的行为是该消息被接收主页面和iframe。我可以通过在页面控制台中看到两个getting page details
实例来验证此情况。
但是,我只收到一个回应浏览器操作的响应(got details
仅在浏览器操作中记录了一次),这似乎只来自主页而不是嵌入式iframe。
如何通过消息传递从页面中嵌入的iframe进行通信?我期待在我的浏览器动作function (details) { }
中发生两次回调。
消息是要走的路。谢谢。 – kspearrin