【问题标题】:Chrome extension: load different content scriptsChrome 扩展:加载不同的内容脚本
【发布时间】:2011-11-25 16:14:01
【问题描述】:

我想根据当前选择的页面和选项卡加载不同的内容脚本。现在,我有三个内容脚本。我想将其中两个用于一页,第三个用于另一页。

属于第1页:

content_script.js load_content_script.js

属于page2:

newtab_content_script.js

现在我的清单看起来像这样

{
  "name": "A plugin for AdData express. Generate an instant excel document from the brands you check mark.",
  "version": "1.0",
  "background_page": "background.html",
  "permissions": [
    "cookies",
    "tabs", 
    "http://*/*", "https://", "*", "http://*/*", "https://*/*",
    "http://www.addataexpress.com", "http://www.addataexpress.com/*"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>","http://*/*","https://*/*"],
      "js": ["load_content_script.js", "content_script.js", "newtab_content_script.js", "jquery.min.js", "json.js"]
    }
  ],
  "browser_action": {
      "name": "AdData Express Plugin",
      "default_icon": "icon.png",
      "js": "jquery.min.js",
      "popup": "popup.html"
  }
}

我将如何在清单或其他地方构建它?

【问题讨论】:

标签: javascript google-chrome permissions google-chrome-extension manifest


【解决方案1】:

为了完整起见,您从清单中执行此操作的方式是根据需要在“content_scripts”下添加尽可能多的 matches 块:

"content_scripts": [
  {
    "matches": ["http://www.google.com/*"],
    "css": ["mygooglestyles.css"],
    "js": ["jquery.js", "mygooglescript.js"]
  },
  {
    "matches": ["http://www.yahoo.com/*"],
    "css": ["myyahoostyles.css"],
    "js": ["jquery.js", "myyahooscript.js"]
  }
],

【讨论】:

  • 这比chrome.tabs.executeScript() 更能防止交叉错误。 +1
【解决方案2】:

您应该使用executeScript,而不是使用绑定到清单中指定的 URL 表达式的内容脚本,它可以让您以编程方式决定何时注入 JS sn-p 或文件:

// background.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // there are other status stages you may prefer to inject after
  if (changeInfo.status === "complete") {
    const url = new URL(tab.url);
    if (url.hostname === "www.stackoverflow.com") {
    
      // this is the line which injects the script
      chrome.tabs.executeScript(tabId, {file: "content_script.js"});
    }
  }
});

确保向 manifest.json 添加tabs 权限:

{
  // ...settings omitted...
  "permissions": [
    "tabs",  // add me
  ]
}

【讨论】:

  • 如果使用executescript从后台页面调用它们,它们是否被视为内容脚本?
  • 它们使用相同的机制注入到页面中,具有相同的限制。
  • 值得一提的是,这需要manifest文件中的tabs权限。
  • 在清单中声明它的缺点是什么?为什么用exceuteScrip'注入更好?我知道executeScript 允许您以编程方式决定何时注入脚本,但如果您总是希望它在某个 url 注入呢?
  • @sbru 在这种情况下,您将使用清单。如果您只想在页面上的特定条件下执行脚本怎么办。这是我在 executeScript 中看到的一个案例。
【解决方案3】:

你应该使用Programmatic injection

chrome.tabs.executeScript(null, {file: "content_script.js"});

【讨论】:

猜你喜欢
  • 2014-11-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2016-12-23
  • 2011-09-28
  • 2021-06-15
相关资源
最近更新 更多