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

Cha*_*yan 19 javascript permissions google-chrome manifest google-chrome-extension

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

属于第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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 79

只是为了完整性,从清单中执行此操作的方式是matches根据需要在"content_scripts"下包含尽可能多的块:

"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"]
  }
],
Run Code Online (Sandbox Code Playgroud)


Bor*_*mus 20

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

chrome.tabs.executeScript(null, {file: "content_script.js"});
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,这需要清单文件中的选项卡权限. (8认同)

wuk*_*ong 5

你应该使用程序化注入

chrome.tabs.executeScript(null, {file: "content_script.js"});
Run Code Online (Sandbox Code Playgroud)