I have started developing browser extensions. I noticed a common concept is that the extension can inject JS code into the current browser tab.
I am a bit puzzled of how that doesn't cause issues on a regular basis.
I mean, how can things still work if I inject version x of JQuery (through my browser extension) in a page that has already included version y of JQuery? Won't there be a conflict for the $()
function?
How is it possible things go that smoothly? Is there any particular technique the developer should employ to make sure such conflicts won't happen, or the browsers take care of everything?
While noConflict()
may work most of the time for jQuery, it is still a bad idea for extensions and doesn't apply to most other libraries or utilities.
The smart thing to do, is do not inject code at all (with one exception1). The extension can include any libraries you need and there are many benefits to doing so:
There is no possibility of conflict with the page's javascript.
There is no dependency on the page's JS, which changes without notice, Your extension will break less often.
When you inject a library, it has to be fetched from some external server. This slows your extension and makes it vulnerable to crashes outside of your control.
When you include the library with your extension, it's: (a) always present, (b) always a known-good version, and (c) loads almost instantly from the local machine, not some far-off server.
Your extension can run, even if the page's javascript is disabled.
Your extension can take advantage of the library and the extension APIs, simultaneously.
Incorporating a library, like jQuery is easy with an extension. For example, with Chrome:
Add the library to the manifest.json
file.
A simple manifest that incorporated jQuery could be:
{
"content_scripts": [ {
"exclude_globs": [ ],
"include_globs": [ "*" ],
"js": [ "jquery.min.js", "myJS.js" ],
"matches": [ "http://stackoverflow.com/*"
]
} ],
"description": "Hello world with jQuery",
"name": "Hello world with jQuery",
"version": "1"
}
The mechanism is similar for Firefox and other browsers.
1 The one exception? For an extension, inject code if, and only if, all of these conditions are met: