Chrome Extension 第二篇--通信

本文详细介绍了Chrome扩展中content script、popup、background之间的通信方式,包括sendMessage、connect、window.postMessage等方法,以及长连接的实现。同时,文章还提到了injected script与content script之间的通信策略,并提供了一个通信Demo供读者实践。

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.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值