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

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

相关推荐
用户479492835691518 分钟前
给客户做私有化部署,我是如何优雅搞定 NPM 依赖管理的?
前端·后端·程序员
资生算法程序员_畅想家_剑魔22 分钟前
Java常见技术分享-12-多线程安全-锁机制
java·开发语言
C_心欲无痕24 分钟前
vue3 - markRaw标记为非响应式对象
前端·javascript·vue.js
qingyun98937 分钟前
深度优先遍历:JavaScript递归查找树形数据结构中的节点标签
前端·javascript·数据结构
胡楚昊37 分钟前
NSSCTF动调题包通关
开发语言·javascript·算法
2401_8370885044 分钟前
简要总结 HashSet 和 HashMap(Java)
java·开发语言
熬夜敲代码的小N1 小时前
Vue (Official)重磅更新!Vue Language Tools 3.2功能一览!
前端·javascript·vue.js
90后的晨仔1 小时前
用 Python 脚本一键重命名序列帧图片的名称
前端
辰同学ovo1 小时前
Vue 2 路由指南:从入门到实战优化
前端·vue.js
小彭努力中1 小时前
1.在 Vue 3 中使用 Cesium 快速展示三维地球
前端·javascript·vue.js·#地图开发·#cesium·#vue3