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,
Asked
Active
Viewed 1.0k times
11
-
3I don't get it. The content scripts and the page are isolated. – Denys Séguret Jun 07 '12 at 08:49
-
@DenysSéguret only the *execution* is isolated, content scripts actually manipulate the same DOM and can inject conflicting code - so this is not that obvious: `Isolated worlds do not allow for content scripts, the extension, and the web page to access any variables or functions created by the others.` So you don't have problem when defining scripts in manifest, unless you start ***injecting*** code from your script. – jave.web Oct 07 '19 at 19:29
1 Answers
29
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

neocotic
- 2,131
- 18
- 18
-
1This isn't an issue due to the way content scripts change the JavaScript environment. The [execution environment](http://code.google.com/chrome/extensions/content_scripts.html#execution-environment) section of the official documentation covers this quite well. – neocotic Jun 07 '12 at 09:11
-
I see that the doc covers exactly the case of jquery : "For example, a content script could include JQuery v1 and the page could include JQuery v2, and they wouldn't conflict with each other." – Denys Séguret Jun 07 '12 at 09:13
-
jQuery itself is just a library and doesn't make any changes that you don't tell it to. Like most libraries common libraries it only exposes its functionality through the use of one or more global variables. If you're using a library that changes the DOM without any instruction you'd probably be aware of it as that behaviour presumably goes hand-in-hand with its functionality. – neocotic Jun 07 '12 at 09:22