2016-11-25 47 views
0

我正在查看嵌入了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) { }中发生两次回调。

回答

1

chrome.runtime.onMessagesendRespnse()功能可用于至多一次发送单个响应于消息。这并不意味着它可以每帧使用一次,但总共可以使用一次。当描述sendResponse功能,Chrome documentation说[重点煤矿]:

函数调用(最多一次)当你有一个响应。参数应该是任何可以用JSON的对象。 如果在同一文档中有多个onMessage侦听器,则只有一个可能发送响应。

因此,您需要使用其他方法将消息发送到后台脚本。这通常是chrome.runtime.sendMessage()(内容脚本)与后台脚本中的chrome.runtime.onMessage侦听器配对。您需要为消息定义一些格式,以定义背景脚本的消息内容。例如,你可以这样做:

内容脚本:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { 
    if(msg.command === 'collectPageDetails') { 
     console.log('getting page details'); 
     chrome.runtime.sendMessage({type:'collectPageDetailsResponse',details:'something'}); 
    } 
}); 

背景脚本:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { 
    if(msg && msg.type === 'collectPageDetailsResponse') { 
     //Received a details response. 
     let tabId = sender.tab.id; 
     let frameId = sender.tab.frameId; 
     console.log('got details:', msg.details, ' From tabId:',tabId, ' frameId:',frameId); 
    } 
}); 
+0

消息是要走的路。谢谢。 – kspearrin

相关问题