Chrome扩展程序:加载不同的内容脚本

25

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

属于页面1:

content_script.js load_content_script.js

属于页面2:

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"
  }
}
我该如何在清单文件或其他地方组织这个结构?

你也可以使用在这个答案中提到的 'chrome.declarativeContent.RequestContentScript'。链接:https://dev59.com/-V8d5IYBdhLWcg3wkS7Y#26677279 - schellmax
您是否考虑将 Darin 的答案 设为最佳答案?它似乎是最直接的解决方案。 - Stevoisiak
3个回答

103

为了完整性起见,从清单文件中实现此操作的方法是在 "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"]
  }
],

1
这比 chrome.tabs.executeScript() 更跨浏览器兼容。+1 - jave.web

25

与在清单中指定的URL表达式绑定的内容脚本不同,你应该使用executeScript,它允许您编程决定何时注入JS片段或文件:

// 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 从后台页面调用它们,那么它们是否被视为内容脚本? - Chamilyan
它们使用相同的机制注入到页面中,并受到相同的限制。 - Boris Smus
8
值得一提的是,这需要在清单文件中添加选项卡权限。 - James
在清单中声明的缺点是什么?为什么用 executeScript 注入更好?我理解 executeScript 可以让你通过编程方式决定何时注入脚本,但是如果你总是想在某个特定的 URL 上注入它,该怎么办? - sbru
在这种情况下,您将使用清单。如果您只想在页面上特定条件下执行脚本,该怎么办?这是我认为executeScript的用例。 - Chamilyan
这个要放到 background.js 文件里吗?我们如何观察每个标签页的新标签和新 URL? - Seph Reed

7
你应该使用程序注入
chrome.tabs.executeScript(null, {file: "content_script.js"});

1
你能解释为什么吗? - r0bb077
请查看我的评论:https://dev59.com/T2sz5IYBdhLWcg3w8Mcb#dU0coYgBc1ULPQZFsRmF - Chamilyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接