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({});

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

相关推荐
程序员鱼皮3 分钟前
我花 300 块,让 Claude Fable 5 开发桌面 APP,值么?
前端
William_Xu8 分钟前
JavaScript 并发控制
前端
拾年2758 分钟前
从零手写 Ajax:用原生 XHR 搭建前后端交互全流程
前端·javascript·ajax
光影少年10 分钟前
懒加载与分包:React.lazy + Suspense
前端·react.js·掘金·金石计划
拉勾科研工作室23 分钟前
区块链工程毕业论文题目【249个】
开发语言·javascript
小林ixn25 分钟前
你以为你懂 + 号?看完这篇 Bun + TS 实战,才发现以前全写错了
前端·javascript·typescript
namexingyun1 小时前
开源前端生态如何成为 AI UI 生成的“燃料“:shadcn/ui、Tailwind CSS、Storybook 技术价值全解剖
java·前端·人工智能·python·ui·开源·ai编程
Zyed1 小时前
[STM32]Day15读写FLASH+读取ID
前端·stm32·性能优化
z落落1 小时前
C#WinForm控件实战:Panel与单选框动态创建
开发语言·c#
ptc学习者1 小时前
python 中描述符@property property 大概的样子
开发语言·python