问题描述
我的Chrome扩展程序有两个文件:内容脚本和后台脚本.我还需要将jQuery添加到cdn的内容脚本中,并将lodash添加到cdn的后台脚本中.
my Chrome extension has two files: content and background scripts. I need to add jQuery to content script from cdn and lodash to background script from cdn too.
在清单中,我试图像这样从CDN添加lodash:
In my manifest I tried to add lodash from cdn like this:
"background": {
"scripts": ["background.js", "https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"]
},
"content_security_policy": "script-src 'self' https://cdn.jsdelivr.net; object-src 'self'"
但这没有帮助.
我的内容文件从后台文件注入到页面中
My content file is injected to the page from the background file:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
chrome.tabs.insertCSS(null, {file: "mainStyles.css"});
chrome.tabs.executeScript(null, {
code: 'var config = ' + JSON.stringify(config)
}, function() {
chrome.tabs.executeScript(null, { file: "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "content.js" })
});
});
}
});
您可以看到,我尝试从cdn包含jQuery,但是这种方式也没有包含.
And as you can see I tried to include jQuery from cdn but this way it's not included either.
也许有人知道该怎么做?提前非常感谢!
Maybe someone knows the way how to do this?Many thanks in advance!
推荐答案
您可以从外部资源获取脚本,但这不是此处.
You can get your scripts from external resources, but it's not the preferred way as stated here.
此外,您不应该这样使用background
标记. 来源
Furthermore, you shouldn't use the background
tag like this. Source
最好下载扩展并将其与所需的库捆绑在一起,并将其作为 content_script .
You're better off downloading and bundling your extension with required libraries and getting it as a content_script.
我的manifest.json
中在youtube上运行的扩展程序的示例:
Example from my manifest.json
for an extension running on youtube:
"content_scripts": [ {
"matches": ["http://*.youtube.com/*", "https://*.youtube.com/*"],
"js": ["jquery.js", "content.js"]
}],
如果必须使用一些外部脚本,我发现使用一点技巧可以达到最佳效果.
If you must use some external scripts, I found that doing it using a little hack works the best.
通常的想法是,它在当前网页的范围内执行一段JS代码,并在您想要的脚本中添加<script>
标签.
The general idea is that it executes a piece of JS code in the scope of current webpage and adds a <script>
tag with your desired script.
这是扩展程序的摘录,其中要求包含一些我们专有的js:
This is a snippet from an extension that required some of our proprietary js to be included:
chrome.tabs.executeScript(tab.id, {code:
"document.body.appendChild(document.createElement('script')).src = 'https://example.com/script.js';"
});
chrome是个好人,就执行它.
And chrome being such a good guy just executes it.
这篇关于Chrome扩展程序|如何在CDN的内容和后台脚本中包含库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!