2 回答

TA贡献1752条经验 获得超4个赞
页面上下文脚本确实不能使用Chrome API。
但是,它可以分派可由内容脚本捕获的DOM事件。
还有就是文档中的例子在这里。除了使用之外window.postMessage,您还可以调度自定义事件。
因此,您需要使内容脚本像页面上下文和背景之间的代理一样工作。遵循以下原则:
// Content script
//Listen for the event
window.addEventListener("PassToBackground", function(evt) {
chrome.runtime.sendMessage(evt.detail);
}, false);
// Page context
var message = {/* whatever */};
var event = new CustomEvent("PassToBackground", {detail: message});
window.dispatchEvent(event);
您可以对此进行概括以将答案传回。

TA贡献1744条经验 获得超4个赞
只是为了对此稍作扩展,在使用gmail.js时,为了将消息发送main.js到扩展页面,您需要使用内容脚本作为中介。该图有望说明。
main.js
|
| window.postMessage();
|
V
content.js //window.addEventListener("message", callback, false);
|
| chrome.runtime.sendMessage();
|
V
background.js //chrome.runtime.onMessage.addListener(callback);
添加回答
举报