Chrome 扩展 background 与content_script 之间通信

content_script 向 background 发消息要用:chrome.runtime.sendMessage

复制代码
        chrome.runtime.sendMessage({event: "xhr", data:option }, function (res) { 
            //option.onload(res);
            //console.log(res);
            if (res.event == "xhr" && !res.err){
                option.onload(res);
            }
        });

background 接收消息:chrome.runtime.onMessage.addListener

javascript 复制代码
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
 if (message.event == "copy") {
       //alert("copy detected");
       //return true;
 }

    sendResponse({});
    return true; 
});

background 向 content_script 发消息要用:chrome.tabs.sendMessage

javascript 复制代码
            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
              if (tabs && tabs.length > 0) {
                const activeTab = tabs[0];
                console.log('当前活动标签页的是:', activeTab);
                try {
                    chrome.tabs.sendMessage(activeTab.id, {'evt':'mediaUrl','data':mediaUrl }, function (res) { 
                        console.log(res);
                    });
                } catch (error) {
                    console.error(error.message);
                }
              }
            });

content_script 接收消息用:chrome.runtime.onMessage.addListener

和background中是一样的,注意其中的 sendResponse({});

这一句很关键,接收到了就要给一个回应;

相关推荐
菜鸟~noob2339 分钟前
【太空电子战】午夜锤行动中的电磁静默区:可逆干扰的实战验证【含matlab代码】
linux·开发语言·matlab·电子战
Ikalus198818 分钟前
三套 API 都告诉我成功了,浏览器一个字都没收到
javascript
开开心心就好22 分钟前
办公软件卸载不干净?专用工具一键清残留
java·前端·人工智能·智能手机·kafka·excel·memcache
Ikalus198831 分钟前
计数器停在 0,我差点把一篇空摘要发出去
javascript
坤坤子吖33 分钟前
Python基础语法学习:条件、循环与程序控制
开发语言·笔记·python·学习
静默回滚37 分钟前
图片能显示,画进canvas却空白:像素面积上限
前端
补码缩写37 分钟前
canvas大图内存怎么算:宽×高×4只是第一份
前端
吠品39 分钟前
volatile到底在拦什么:SysTick->VAL读的哪格
java·服务器·开发语言
coding漫漫长路42 分钟前
img.decode()报错的图能画,load成功的却是空的
前端
不可能片场44 分钟前
AI视频首尾帧控制 用参考图定住镜头
前端·electron