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

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

相关推荐
Mh12 小时前
基于踩过的坑,浅聊一下vh、svh、lvh、dvh
前端·css·设计模式
刘小灰12 小时前
返璞归真,我开始更新博客了
前端·后端
郝学胜-神的一滴14 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove14 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
圆心角14 小时前
Agent 上下文原理:为什么“记住”比“推理”更难
前端·面试·agent
代码民工正电荷15 小时前
JAVA学习基础(一)
java·开发语言·学习
杜子不疼.17 小时前
从 Apache HTTP Server 到 CivetWeb:在鸿蒙 PC 的 3.1 MiB HAP 里嵌入 Web 服务器
前端·apache·harmonyos
kyriewen18 小时前
AI 生成率进了 KPI,最慌的是写代码最快的人
前端·javascript·程序员
SoaringHeart18 小时前
Flutter组件封装:聊天气包图片组件NChatBubble
前端·flutter
星恒随风18 小时前
C++11 加餐(2)并发支持库——mutex、lock_guard、unique_lock 与死锁问题
开发语言·c++