我需要從 Content Script 運行一些 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);
uj5u.com熱心網友回復:
是的。
如果您想在正文之前訪問 jquery,那么在 manifest.json 檔案中使用“document_start”而不是“document_end”。
回答 1。
將它包含在 manifest.json 中的內容腳本之前。
- 下載您要使用的 jquery 版本。
- 在 manifest.json 中指定
清單.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://www.uj5u.com/qiye/489044.html
