【问题标题】:Chrome extension's content scripts doesn't affect a particular websiteChrome 扩展的内容脚本不会影响特定网站
【发布时间】:2018-06-21 16:43:58
【问题描述】:

我有一个 chrome 扩展程序,它使用内容脚本将特定单词注入网页。它适用于某个网站 x,但不适用于 y。

清单

 {
  "name": "test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "word",
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": true
  },
  "browser_action": {
    "default_title": "chat"
  },
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs"
  ]
}

Background.js

// listen for our browerAction to be clicked

    chrome.browserAction.onClicked.addListener(function (tab) {
        // for the current tab, inject the "inject.js" file & execute it
        chrome.tabs.executeScript(tab.ib, {
            file: 'inject.js'
        });
    });

注入.js

// this is the code which will be injected into a given page...
(function() {
// just place a div at top right
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.top = 600;
div.style.right = 700;
div.textContent = 'Hello!';
document.body.appendChild(div);
})();

此代码适用于在网站中添加单词:https://developer.chrome.com/extensions/examples/api/browserAction/make_page_red/background.js

不适用于 web.whatsapp.com 以及其他常见网站。

【问题讨论】:

  • 您是否检查过开发者控制台是否有任何错误?也许该网站阻止了内容脚本。
  • 您是否尝试添加匹配项" : ["://*/"] ?
  • @elegant-user 不,那没用 :(
  • 显示您的代码。请否则我们无法为您提供帮助。
  • 当然,您需要清单还是脚本?

标签: javascript json google-chrome google-chrome-extension content-script


【解决方案1】:

刚刚将"*://*/*", 添加到您的清单中以使其正常工作。

manifest.json

{
  "name": "test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "word",
  "background": {
    "scripts": [
      "background.js"
    ],
    "persistent": true
  },
  "browser_action": {
    "default_title": "chat"
  },
  "permissions": [
    "*://*/*",
    "tabs"
  ]
}

background.js

// listen for our browerAction to be clicked

    chrome.browserAction.onClicked.addListener(function (tab) {
        // for the current tab, inject the "inject.js" file & execute it
        chrome.tabs.executeScript(tab.ib, {
            file: 'inject.js'
        });
    });

注入.js

(function() {
    console.log("Inject successfully.");
    // just place a div at top right
    var div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.top = 600;
    div.style.right = 700;
    div.style.zIndex = 9999;
    div.textContent = 'Hello!';
    document.body.appendChild(div);
})();

【讨论】:

  • 我在smashingmagazine.com 上遇到了同样的问题,我的内容脚本没有加载到我在那里尝试过的任何页面上。我尝试按照推荐添加权限“://*/”和“”,没有区别,我遇到的其他网站也不需要。我正在使用一个非常宽松的清单,“匹配”:[“http://*/*”,“https://*/*”]。不明白。欢迎提出任何想法。
猜你喜欢
  • 1970-01-01
  • 2011-08-13
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2015-12-24
相关资源
最近更新 更多