使用内容脚本+后台脚本

时间:2017-02-16 23:44:46

标签: google-chrome-extension content-script

我正在尝试编写一个chrome扩展来将一些数据从站点1发送到站点2.我创建了两个内容脚本(每个站点)和一个后台脚本。以下是我正在处理的错误的脚本和解释。

清单文件:

{
  "name": "Testing",
  "version": "0.0.5",
  "manifest_version": 2,
  "description": "Testing",
  "homepage_url": "https://www.test.co.uk",
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "default_locale": "en",
  "background": {
    "scripts": [ "src/bg/background.js" ],
    "persistent": true
  },
  "page_action": {
    "default_icon": "icons/icon19.png",
    "default_title": "page action demo",
    "default_popup": "src/page_action/page_action.html"
  },
  "permissions": [
    "tabs",
    "*://www.site1.co.uk/*",
    "*://site1.co.uk/*",
    "*://www.site2.co.uk/*",
    "*://site2.co.uk/*"
  ],
  "content_scripts": [
    {
      "matches": [
        "*://www.site1.co.uk/*",
        "*://site1.co.uk/*"
      ],
      "js": [
        "src/inject/inject-pg1.js"
      ]
    },
    {
      "matches": [
        "*://www.site2.co.uk/*",
        "*://site2.co.uk/*"
      ],
      "js": [
        "src/inject/inject-pg2.js"
      ]
    }
  ]
}

后台脚本

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

  if (request.data) {
      console.log(request.data);

      if (request.data == "pg1") {
          chrome.tabs.query({ active: true },
              function (tabs) {
                  chrome.tabs.sendMessage(tabs[0].id, { data: "from page 1" }, function (response) { });
              });
      }

      if (request.data == "pg2") {
          chrome.tabs.query({ active: true },
              function (tabs) {
                  chrome.tabs.sendMessage(tabs[0].id, { data: "frome page 2" }, function (response) { });
              });
      }
  }

  chrome.pageAction.show(sender.tab.id);
  sendResponse();
});

Page 1 inject-pg1.js:

chrome.runtime.sendMessage({
    data: 'pg1'
});


chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {    
      if (request.data) {
          if (request.data == "pg2") {
              console.log("from page 2")
          }
      }
  });

Page 2 inject-pg2.js:

chrome.runtime.sendMessage({
    data: 'pg2'
});


chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {    
      if (request.data) {
          if (request.data == "pg1") {
              console.log("from page 1")
          }
      }
  });

有2个网站,每个网站都有自己的内容脚本。当加载页面1时,它会向后台脚本发送一条消息,如果从第1页或第1页收到消息,它将根据条件向第2页发送消息。

但是在第2页上没有收到消息,这是因为它在另一个标签中?我有时也会在Error in response to tabs.query: TypeError: Cannot read property 'id' of undefined

中的background.js tabs[0].id中收到错误

这是实现此目的的正确方法,还是可能的?如果有更好的解决方案,请指出正确的方向。三江源

0 个答案:

没有答案