javascript Chrome 扩展:加载不同的内容脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7563379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome extension: load different content scripts
提问by Chamilyan
I want to load a different content script depending on the page and tab that is currently selected. Right now, I have three content scripts. I want to use two of them for one page and the third one for another page.
我想根据当前选择的页面和选项卡加载不同的内容脚本。现在,我有三个内容脚本。我想在一页上使用其中的两个,在另一页上使用第三个。
Belonging to page 1:
属于第1页:
content_script.js
load_content_script.js
content_script.js
load_content_script.js
Belonging to page2:
属于page2:
newtab_content_script.js
newtab_content_script.js
right now my manifest looks like this
现在我的清单看起来像这样
{
"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"
}
}
how would I structure this in the manifest or elsewhere?
我将如何在清单或其他地方构建它?
回答by Darin
Just in the interest of completeness, the way you'd do this from the manifest is to have as many matches
blocks under "content_scripts" as needed:
为了完整起见,您从清单中执行此操作的方式是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"]
}
],
回答by Boris Smus
Rather than using content scripts that are bound to URL expressions specified in the manifest, you should use executeScript, which lets you programmatically decide when to inject a JS snippet or file:
您应该使用executeScript,而不是使用绑定到清单中指定的 URL 表达式的内容脚本,它允许您以编程方式决定何时注入 JS 片段或文件:
chrome.tabs.executeScript(null, {file: "content_script.js"});
回答by wukong
you should use Programmatic injection
你应该使用程序化注入
chrome.tabs.executeScript(null, {file: "content_script.js"});