Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - Chrome Extension | How to include library in content and background scripts from 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.

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'"

But that didn't help.

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" })
            });
        });
    }
});

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can get your scripts from external resources, but it's not the preferred way as stated here.

Furthermore, you shouldn't use the background tag like this. Source

You're better off downloading and bundling your extension with required libraries and getting it as a content_script.

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.

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.

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';"
});

And chrome being such a good guy just executes it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...