将jQuery注入当前标签页 - chrome扩展名

问题描述 投票:0回答:2

我是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>

如果我将chrome-extension://abdiolbenneaffeaedmfeeanlephlnoo/jquery.js放入URL我可以访问它。

- 编辑

如果我从外部加载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');
google-chrome-extension
2个回答
0
投票

如果你想在你的扩展背景页面中注入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的信息。


0
投票

这真的很奇怪。您可能检查过jquery.js文件是否在根文件夹中并且使用此名称,对吗?

好吧,在我的情况下,我想在content_scripts > matches中匹配的所有页面中添加jQuery,所以我只是做了类似这样的事情:

...
"content_scripts": [
    {
        "matches": [
            "https://*/*"
        ],
        "js": [
            "assets/js/jquery.js",
            "assets/js/contentscript.js"
        ]
    }
],
...

所以这样我可以在contentscript.js文件中使用jQuery。

© www.soinside.com 2019 - 2024. All rights reserved.