[英]Chrome extension: load different content scripts
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
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?我将如何在清单或其他地方构建它?
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:为了完整起见,您从清单中执行此操作的方式是根据需要在“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"]
}
],
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 片段或文件:
// 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"});
}
}
});
Make sure to add tabs
permission to manifest.json:确保向 manifest.json 添加tabs
权限:
{
// ...settings omitted...
"permissions": [
"tabs", // add me
]
}
你应该使用 程序化注入
chrome.tabs.executeScript(null, {file: "content_script.js"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.