Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jquery in a chrome extension content script when an older version is already on the page

I'm writing a chrome extension that fiddles around with the layout of a page. I want to use the latest version of jQuery to do this.

The page in question already includes version 1.4.4 of jQuery as part of one of their scripts.

If I include the newer version of jQuery, the page hangs. How can I include the newest version of jQuery so that it is only available to my content script, and doesn't affect scripts already on the page?

like image 389
Eric Avatar asked Aug 27 '11 10:08

Eric


People also ask

Can I use both JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.

What is jQuery noConflict()?

In jQuery's case, $ is just an alias for jQuery, so all the functionality is available without using $. Run $. noConflict() method to give control of the $ variable back to whichever library first implemented it. This helps us to make sure that jQuery doesn't conflict with the $ object of other libraries.

What is content_ script js?

"content_scripts": [ { "matches": ["*://*.mozilla.org/*"], "js": ["borderify.js"] } ] Instructs the browser to load content scripts into web pages whose URL matches a given pattern. This key is an array.

Can you make a Chrome extension with JavaScript?

A chrome extension is a program that is installed in the Chrome browser that enhances the functionality of the browser. You can build one easily using web technologies like HTML, CSS, and JavaScript.


2 Answers

If you inject your jquery as a content script it will be sandboxed, you won't be having any conflicts no matter what a parent page is using.

like image 148
serg Avatar answered Sep 19 '22 07:09

serg


You can essentially namespace differing jQuery versions by using its No Conflict mode and executing your code in a closure. For instance:

<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jq162 = jQuery.noConflict(true);
    (function ($) {
        $(function () {
            // Your document ready code here
        });
    })(jq162);
</script>

Please note this declaration makes jq162 available to the global scope so it can be reused elsewhere. If you'd prefer to scope the instance of jQuery locally, make it a var.

like image 45
lsuarez Avatar answered Sep 22 '22 07:09

lsuarez