Chrome Extension | How to include library in content and background scripts from cdn

后端 未结 1 2046
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 10:20

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 m

相关标签:
1条回答
  • 2020-12-29 10:57

    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.

    0 讨论(0)
提交回复
热议问题