我需要运行一些jQuery代码的内容脚本,但有些网站不包括jQuery,有任何方法注入吗?我试过了,但似乎一点用也没有
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
发布于 2022-06-08 07:29:22
是。
如果您想在
之前访问jquery,那么在manifest.json文件中使用"document_start“代替"document_end”。
回答1。
在manifest.json中的内容脚本之前包含它。
中指定它。
manifest.json
{
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<tab_url_pattern>"],
"run_at": "document_end",
"js": ["jquery3.5.1.min.js", "contentScript.js"],
"all_frames": false
},
]
}
回答2。
使用"Web_accessible_resource“公开jquery文件,并使用document.body.appendChild()将其注入必需的选项卡
{
"manifest_version":3,
"permissions": ["tabs"],
"content_scripts":[{
"matches": ["<url_pattern_1>"],
"run_at": "document_end",
"js": ["contentScript.js"],
"all_frames": false
}],
"web_accessible_resources": [
{
"resources": ["jquery-1.11.3.min.js", "otherJquery.js"],
"matches": ["<url_pattern_1>"]
}
]
}
在contentScript.js中
const contentScriptLinks = ['jquery-1.11.3.min.js', 'otherJquery.js'];
contentScriptLinks.forEach(src => {
let el = document.createElement('script');
el.src = chrome.runtime.getURL(src);
document.body.appendChild(el);
});
https://stackoverflow.com/questions/72540524
复制相似问题