runtime.onConnect
当与扩展进程或内容脚本建立连接时触发。
语法
js
browser.runtime.onConnect.addListener(listener)
browser.runtime.onConnect.removeListener(listener)
browser.runtime.onConnect.hasListener(listener)
事件有三个函数
addListener(listener)-
向此事件添加监听器。
removeListener(listener)-
停止监听此事件。
listener参数是要移除的监听器。 hasListener(listener)-
检查此事件是否已注册
listener。如果正在侦听,则返回true,否则返回false。
addListener 语法
参数
function-
当此事件发生时调用的函数。该函数将传递此参数
port-
一个
runtime.Port对象,用于连接当前脚本与正在连接的另一个上下文。
示例
此内容脚本
- 连接到后台脚本,并将
Port存储在名为myPort的变量中 - 监听
myPort上的消息,并记录它们 - 当用户点击文档时,使用
myPort向后台脚本发送消息
js
// content-script.js
let myPort = browser.runtime.connect({ name: "port-from-cs" });
myPort.postMessage({ greeting: "hello from content script" });
myPort.onMessage.addListener((m) => {
console.log("In content script, received message from background script: ");
console.log(m.greeting);
});
document.body.addEventListener("click", () => {
myPort.postMessage({ greeting: "they clicked the page!" });
});
相应的后台脚本
-
监听来自内容脚本的连接尝试
-
当收到连接尝试时
- 将端口存储在名为
portFromCS的变量中 - 使用端口向内容脚本发送消息
- 开始监听端口接收到的消息,并记录它们
- 将端口存储在名为
-
当用户点击扩展的浏览器操作时,使用
portFromCS向内容脚本发送消息
js
// background-script.js
let portFromCS;
function connected(p) {
portFromCS = p;
portFromCS.postMessage({ greeting: "hi there content script!" });
portFromCS.onMessage.addListener((m) => {
console.log("In background script, received message from content script");
console.log(m.greeting);
});
}
browser.runtime.onConnect.addListener(connected);
browser.browserAction.onClicked.addListener(() => {
portFromCS.postMessage({ greeting: "they clicked the button!" });
});
浏览器兼容性
加载中…
注意:此 API 基于 Chromium 的 chrome.runtime API。本文档源自 Chromium 代码中的 runtime.json。