How to use jQuery in Chrome extensions contentscri

2019-01-15 01:20发布

问题:

how can I use jQuery in my google chrome extension without conflicting with the scripts on the webpage? because when I use jQuery and another script on the webpage uses $, my content script dies or that webpage dies,

回答1:

The real answer is that you don't need to use "self-running private functions". You need to understand that content scripts are executed in isolation so cannot conflict with resources used by websites by design.

If you want to use a library in your content script the preferred method is to simply include it in your extension/app and then load it first in your manifest;

{
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "js": ["jquery.js", "myscript.js"]
    }
  ]
  ...
}

This will result in jquery.js being loaded in to your private content script environment and then myscript.js. Your code will be much cleaner and modular as it doesn't contain minified code for external libraries.

Source: https://developer.chrome.com/extensions/content_scripts