我刚接触chrome扩展,所以我可能用错了术语。
我已经创建了一个扩展
manifest.json
{
"name": "Run code in page",
"version": "1.1",
"manifest_version": 2,
"content_scripts": [{
"js": ["contentscript.js"],
"matches": ["https://*/*"]
}],
"web_accessible_resources": ["*.js"],
"default_locale": "en"
}
contentscript.js
function injectScript(script) {
var s = document.createElement('script');
s.src = chrome.extension.getURL(script);
(document.head || document.documentElement).appendChild(s);
}
injectScript('script.js');
injectScript('otherscript.js');
script.js
console.log('script.js');
otherscript.js
console.log('otherscript.js');
这是可行的,我在输出中看到了以下内容:
script.js
otherscript.js
一切都很好,两个脚本都在加载,我需要以相同的方式添加jQuery,以便我可以从我的脚本访问jQuery。
所以,我
injectScript('jquery.js');
但是现在我得到了以下错误
Denying load of chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/jquery.js. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
如果我看一下DOM,我会看到这个
<script src="chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/script.js"></script>
<script src="chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/otherscript.js"></script>
<script src="chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/jquery.js"></script>
如果我在URL中输入chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/jquery.js,我就可以访问它。
--编辑
如果我从外部加载jquery,它就会加载,所以我想我可以这样做。例如
function injectExternalScript(script) {
var s = document.createElement('script');
s.src = script;
(document.head || document.documentElement).appendChild(s);
}
injectExternalScript('https://code.jquery.com/jquery-3.3.1.min.js');
发布于 2018-06-08 03:17:39
如果你想在你的扩展后台页面中注入jQuery,在manifest.json
中这样做:
示例:
"background": {
"persistent": true,
"scripts": ["jquery-3.3.1.min.js", "background.js"]
},
注意:确保jQuery是数组中的第一个,以便它在实际background.js
之前加载
但是,在你的例子中是,你没有在后台执行代码,也没有向它注入任何东西,因为你把一个内容脚本误认为是你没有的背景页面。
我建议您先阅读有关Chrome Extension Architecture的官方文档,然后再做其他事情。
您还可以在content.js
中编写这样的代码,以便从内容脚本直接注入到DOM中,这样就可以避免在扩展中使用多个不必要的.js
文件。
Content.js:
//Injects functions directly into the dom
function inject(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); // run the script
document.body.removeChild(script); // clean up
}
inject(function(){
// code that will be executed in the scope of the page
}
您可以阅读有关此here的更多信息。
发布于 2018-06-08 16:27:49
这真的很奇怪。您可能检查了jquery.js
文件是否在根文件夹中,并使用此名称,对吗?
嗯,在我的例子中,我想在content_scripts > matches
中匹配的所有页面中添加jQuery,所以我只做了如下操作:
...
"content_scripts": [
{
"matches": [
"https://*/*"
],
"js": [
"assets/js/jquery.js",
"assets/js/contentscript.js"
]
}
],
...
这样我就可以在contentscript.js
文件中使用jQuery了。
https://stackoverflow.com/questions/50748632
复制相似问题