Arv*_*ind 3 google-chrome-extension
在Google Chrome扩展程序中,我想在内容脚本和弹出页面之间传递消息.我还希望在弹出页面向内容脚本发送执行此操作的信号时触发内容脚本中的函数.
Google Chrome扩展程序开发者文档中的消息部分指出,消息可以"从您的内容脚本传递到扩展程序页面,反之亦然"(引自http://code.google.com/chrome/extensions/messaging. HTML)
这是否意味着我可以在内容脚本和弹出页面之间发送/接收消息?因为我看到的用法是用于后台页面和内容脚本之间的通信.
或者我是否必须设置3路消息传递路由 - 即.内容脚本< - >后台页面< - >弹出页面.如果是这种情况,如何在后台页面< - >弹出页面之间设置消息?
在从弹出页面向内容脚本发送信号后,如何在内容脚本中触发函数?这是否还需要后台脚本?
内容脚本只能向后台页面发送消息.如果要将消息从内容脚本发送到弹出窗口,则必须:
将消息从内容脚本发送到后台页面.
chrome.runtime.sendMessage( ...message... , function() { /*response*/ });
Run Code Online (Sandbox Code Playgroud)在后台接收消息.
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { ... });
Run Code Online (Sandbox Code Playgroud)将消息传递给弹出窗口.要获取window对弹出窗口的全局对象的引用,请使用chrome.extension.getViews.注意:与大多数其他chrome API不同,此方法是同步的:
var popupWindows = chrome.extension.getViews({type:'popup'});
if (popupWindows.length) { // A popup has been found
// details is the object from the onMessage event (see 2)
popupWindows[0].whatever(message, sendResponse);
}
Run Code Online (Sandbox Code Playgroud)在弹出窗口中,定义whatever方法.
function whatever(message, sendResponse) {
// Do something, for example, sending the message back
sendResponse(message);
}
Run Code Online (Sandbox Code Playgroud)sendResponse调用(4)时,调用details.sendResponse(见3).反过来,这function() { /*response*/ }来自1.注意:chrome.runtime.sendMessage/ onMessage仅在Chrome 26+中受支持.chrome.extension.sendMessage如果您还想支持旧浏览器,请使用.
| 归档时间: |
|
| 查看次数: |
3464 次 |
| 最近记录: |