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

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

相关推荐
吃饺子不吃馅9 分钟前
为什么SnapDOM 比 html2canvas截图要快?
前端·javascript·面试
这里有鱼汤34 分钟前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
用户21411832636021 小时前
dify案例分享-免费玩转 AI 绘图!Dify 整合 Qwen-Image,文生图 图生图一步到位
前端
IT_陈寒1 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell8 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip8 小时前
Node.js 子进程:child_process
前端·javascript
excel11 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel12 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼14 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping14 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript