Chrome Extension 第二篇 – 通信
Chrome Extension JS 对比
JS 种类 | 可访问的 API | DOM 访问情况 | JS 访问情况 | 直接跨域 |
---|---|---|---|---|
background js | 可以访问绝大部分的 API,除了 devtools 系列 | 不能直接访问 | 不可以 | 可以 |
content scripts | 只能访问 extension、runtime 等部分 API | 可以访问 | 不可以 | 不可以 |
browser action | 可以访问绝大部分的 API,除了 devtools 系列 | 不能直接访问 | 不可以 | 可以 |
inject script | 和普通 JS 无任何差别,不能访问任何扩展 API | 可以访问 | 可以访问 | 不可以 |
通信
content script 向扩展程序通信
// content script
chrome.runtime.sendMessage({
greeting: "您好" }, function (response) {
console.log("收到来自后台的回复:" + response);
});
// background.js 或者 popup.js(browser action)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log("收到来自content-script的消息:");
console.log(request, sender, sendResponse);
sendResponse("我是后台,我已收到你的消息:" + JSON.stringify(request));
});
注意: 如果多个页面都监听 onMessage 事件,对于某一次事件只有第一次调用 sendResponse() 能成功发出回应,所有其他回应将被忽略。
在 content script 中 使用 sendMessage 发送消息,在接收方使用 runtime.onMessage 或者 runtime.onMessageExternal ,向自己的扩展程序发送消息就接受方使用 onMessage,如果是向另一个扩展程序发送则使用 onMessageExternal 。
扩展程序向 coentent script 发送信息使用的就是 tabs.sendMessage
// 唯一的区别是您需要指定发送至哪一个标签页
chrome.tabs.query({
active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
greeting: "您好" }, function (
response
) {
console.log(response.farewell)