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

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

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

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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-08 18:20:06       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-08 18:20:06       5 阅读
  3. 在Django里面运行非项目文件

    2024-06-08 18:20:06       4 阅读
  4. Python语言-面向对象

    2024-06-08 18:20:06       5 阅读

热门阅读

  1. 强化学习面试题

    2024-06-08 18:20:06       20 阅读
  2. 嵌入式C语言面试题笔试题

    2024-06-08 18:20:06       15 阅读
  3. kubesphere报错

    2024-06-08 18:20:06       17 阅读
  4. 物联网的应用——工业自动化

    2024-06-08 18:20:06       16 阅读
  5. 前端判断数据类型的方法有哪些?

    2024-06-08 18:20:06       14 阅读
  6. html+css示例

    2024-06-08 18:20:06       15 阅读
  7. spring入门aop和ioc

    2024-06-08 18:20:06       11 阅读
  8. Golang:go-redis支持Redis Server和Redis Cluster的客户端

    2024-06-08 18:20:06       15 阅读
  9. H3C网络设备配置命令

    2024-06-08 18:20:06       13 阅读
  10. 【游戏】赚钱模拟器2.2版小改进

    2024-06-08 18:20:06       14 阅读