前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >chrome插件的通讯

chrome插件的通讯

作者头像
biaoblog.cn 个人博客
发布2022-08-11 19:24:42
5540
发布2022-08-11 19:24:42
举报
文章被收录于专栏:web技术开发分享

1.先在contentScript里面创建一个端口,并且发送一个消息

contentScript.js

代码语言:javascript
复制
      saveDetail() {
        var port = chrome.extension.connect({ name: "menu" });
        port.postMessage({ detail: { name: "hello!?~" } });

                //这里主要是为了接受回传的值
        port.onMessage.addListener((msg) => {
          if (msg.res) {
            console.log(msg.res);
          }
        });
      },
    },

2.然后在background.js里面接受,并且进行api访问,拿到结果再回传给contentScript

background.js

代码语言:javascript
复制
chrome.extension.onConnect.addListener(function (port) {
  console.log(port);
  if (port.name === "menu") {
    port.onMessage.addListener(function (msg) {
      if (msg.detail) {
        axios.get("http://biaoblog.run:3000/blogData/mood").then((res) => {
          port.postMessage({ res });
        });
      }
    });
  }
});

3.添加popup向contentScript发送消息的实例

popup.js

代码语言:javascript
复制
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (
      response
    ) {
      console.log(response.farewell);
    });
  });

contentScript

代码语言:javascript
复制
  chrome.runtime.onMessage.addListener(function (
    request,
    sender,
    sendResponse
  ) {
    console.log(
      sender.tab
        ? "from a content script:" + sender.tab.url
        : "from the extension"
    );
    if (request.greeting == "hello") {
      sendResponse({ farewell: "I'm contentscript,goodbye!" });
    }
  });

最后记得在manifest.json中添加background配置:

代码语言:javascript
复制
  "background": {
    "scripts": ["lib/axios.js", "background.js"]
  },

参考文档:http://chrome.cenchy.com/messaging.html

https://blog.csdn.net/zhongping136/article/details/16869819?utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-1.control

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • contentScript.js
  • background.js
  • popup.js
  • contentScript
  • 最后记得在manifest.json中添加background配置:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档