888

Is there an easy way to include jQuery in the Chrome JavaScript console for sites that do not use it? For example, on a website I would like to get the number of rows in a table. I know this is really easy with jQuery.

$('element').length;

The site does not use jQuery. Can I add it in from the command line?

6
  • 4
    For more of an automated approach you can use a userscript to include it. Seriously this would be like a 5 line userscript :P
    – rlemon
    Commented Jun 19, 2012 at 13:26
  • 10
    document.getElementById('tableID').rows.length. If the table doesn't have an ID, use the DOM editor to give it one. You don't need jQuery for something so absurdly trivial. Commented Oct 23, 2013 at 21:24
  • 1
    There is a chrome extension to do this - chrome.google.com/webstore/detail/script-injector/… Commented Apr 20, 2014 at 10:27
  • 2
    add it to a script tag, either from cdn or locally. CDN is much simpler.
    – Donato
    Commented Mar 13, 2015 at 3:57
  • 2
    I believe most of the major browsers' Dev Tools now include jQuery (and a few other popular libraries like Underscore) by default, but am unable to find documentation of it. Pop open the console it usually Just Works (tm). ------ Also, this approach has (now) long since been built into a handy bookmarklet by several people. I have used this one successfully: learningjquery.com/2009/04/….
    – brichins
    Commented May 24, 2016 at 17:08

23 Answers 23

1589

Run this in your browser's JavaScript console, then jQuery should be available...

var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();

NOTE: if the site has scripts that conflict with jQuery (other libs, etc.) you could still run into problems.

Update:

Making the best better, creating a Bookmark makes it really convenient, let's do it, and a little feedback is great too:

  1. Right click the Bookmarks Bar, and click Add Page
  2. Name it as you like, e.g. Inject jQuery, and use the following line for URL:

javascript:(function(e,s){e.src=s;e.onload=function(){jQuery.noConflict();console.log('jQuery injected')};document.head.appendChild(e);})(document.createElement('script'),'//code.jquery.com/jquery-latest.min.js')

Below is the formatted code:

javascript: (function(e, s) {
    e.src = s;
    e.onload = function() {
        jQuery.noConflict();
        console.log('jQuery injected');
    };
    document.head.appendChild(e);
})(document.createElement('script'), '//code.jquery.com/jquery-latest.min.js')

Here the official jQuery CDN URL is used, feel free to use your own CDN/version.

4
  • 222
    This snippet didn't work for me. Had no time to figure it out why. Just copied code.jquery.com/jquery-latest.min.js file content and pasted into console. Works perfect. Commented Nov 22, 2012 at 11:32
  • couldn't this be written as: ``` javascript: (function(e, s) { var element = document.createElement('script'); var jqueryUrl = '//code.jquery.com/jquery-latest.min.js'; element.src = jqueryUrl; element.onload = function() { jQuery.noConflict(); console.log('jQuery injected'); }; document.head.appendChild(e); }) ``` ?
    – nicusor
    Commented Nov 10, 2021 at 19:52
  • @RuslanasBalčiūnas, had time to figure it out, added a solution that works with bookmarks. stackoverflow.com/a/76834783/2707890
    – elbajo
    Commented Aug 4, 2023 at 9:56
  • The URL 'code.jquery.com/jquery-latest.min.js' contains jQuery v.1.11.1, which is a very old version (here's the explanation why). You should use specific version insted. Commented Nov 15, 2023 at 20:10
281

Run this in your console:

var script = document.createElement('script'); script.src = "https://code.jquery.com/jquery-3.7.1.min.js"; document.getElementsByTagName('head')[0].appendChild(script);

It creates a new script tag, fills it with jQuery, and appends to the head.

0
124

Copy everything from:
https://code.jquery.com/jquery-3.4.1.min.js

And paste it into console. Works perfectly.

1
  • 25
    Works like a charm! And it doesn't add script to DOM which sometimes it's not possible due to 'Content Security Policy Directive'. I've tried accepted answer which resulted in: Refused to load the script 'ajax.googleapis.com/ajax/libs/jquery/1/jquery.js' because it violates the following Content Security Policy directive: "script-src .... Commented Feb 2, 2013 at 11:10
67

Use the jQueryify booklet:

https://web.archive.org/web/20190502132317/http://marklets.com/jQuerify.aspx

Instead of copy pasting the code in the other answers, this'll make it a clickable bookmark.

0
40

Post 2020 method, using:

(async () => {
  await import('https://code.jquery.com/jquery-2.2.4.min.js')
  // Library ready
  console.log(jQuery)
})()


Without using async, and since import does return a Promise, we have to use .then() :

import('https://code.jquery.com/jquery-2.2.4.min.js')
  .then( () => {
    console.log(jQuery)
  }
)

Another example

https://caniuse.com/es6-module-dynamic-import

0
31

Adding to @jondavidjohn's answer, we can also set it as a bookmark with URL as the javascript code.

Name: Include Jquery

Url:

javascript:var jq = document.createElement('script');jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";document.getElementsByTagName('head')[0].appendChild(jq); setTimeout(function() {jQuery.noConflict(); console.log('jQuery loaded'); }, 1000);void(0);

and then add it to the toolbar of Chrome or Firefox so that instead of pasting the script again and again, we can just click on the bookmarklet.

Screenshot of bookmark

0
30

I'm a rebel.

Solution: don't use jQuery. jQuery is a library to abstract the DOM inconcistencies across the browsers. Since you're in your own console, you don't need this kind of abstraction.

For your example:

$$('element').length

($$ is an alias to document.querySelectorAll in the console.)

For any other example: I'm sure I can find anything. Especially if you're using a modern browser (Chrome, FF, Safari, Opera).

Besides, knowing how the DOM works wouldn't hurt anyone, it would only increase your level of jQuery (yes, learning more about javascript makes you better at jQuery).

0
14

I just made a jQuery 3.2.1 bookmarklet with error-handling (only load if not already loaded, detect version if already loaded, error message if error while loading). Tested in Chrome 27. There is no reason to use the "old" jQuery 1.9.1 on Chrome browser since jQuery 2.0 is API-compatible with 1.9.

Just run the following in Chrome's developer console or drag & drop it in your bookmark bar:

javascript:((function(){if(typeof(jQuery)=="undefined"){window.jQuery="loading";var a=document.createElement("script");a.type="text/javascript";a.src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";a.onload=function(){console.log("jQuery "+jQuery.fn.jquery+" loaded successfully.")};a.onerror=function(){delete jQuery;alert("Error while loading jQuery!")};document.getElementsByTagName("head")[0].appendChild(a)}else{if(typeof(jQuery)=="function"){alert("jQuery ("+jQuery.fn.jquery+") is already loaded!")}else{alert("jQuery is already loading...")}}})())

Readable source-code is available here

0
10

The top answer, by jondavidjohn is good but I'd like to tweak it to address a couple of points:

  • Various browsers issue a warning when loading a script from http to a page on https.
  • Just changing jquery.com's protocol to https results in a warning if you try it straight from the browser's URL bar: This is probably not the site you are looking for!
  • I like to use Google's CDN when I'm using the console to experiment with Google sites such as Gmail.

My only issue is that I have to include a version number where in the console I really always want the latest.

var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();
0
8

Per this answer:

fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))

For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.

This is the equivalent if your browser isn't so modern:

fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})
0
5

It's pretty easy to do this manually, as the other answers explain. But there's also the jQuerify plug-in.

4
  • +1 - Thanks Ken. The word jQuerify reminded me that I created a bookmarklet to do this. I added my own answer that had the code I used. I knew I had done this before =).
    – mrtsherman
    Commented Sep 19, 2011 at 16:57
  • 2
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
    – adamb
    Commented Feb 7, 2018 at 20:19
  • @adamb, unfortunately, along with the tendency of old links to decay, my time and motivation to improve some of these very old answers has concomitantly dissipated over the years. Thanks to the design of SO, however, you are more than welcome to improve the answer yourself — a contribution to the struggle against entropy that is always heartily appreciated.
    – Ken Redler
    Commented Apr 30, 2018 at 4:40
  • link is dead :(
    – sergiol
    Commented Mar 11, 2023 at 23:49
5

FWIW, Firebug embeds the include special command, and jquery is aliased by default: https://getfirebug.com/wiki/index.php/Include

So in your case, you just have to type :

include("jquery");

Florent

0
3

this answer based on @genesis answer, at first I tried the bookmark version @jondavidjohn, and it is not working, so I change it to this (add it to your bookmark):

javascript:(function(){var s = document.createElement('script');s.src = "//code.jquery.com/jquery-2.2.4.min.js";document.getElementsByTagName('head')[0].appendChild(s);console.log('jquery loaded')}());

words of caution, is not tested in chrome but work in firefox, and not tested in conflict environment.

0
3

Modern browsers (tested on Chrome, Firefox, Safari) implement some helper functions using the dollar sign $ that are very similar to jQuery (if the website doesn't define something using window.$).

Those utilities are quite useful for selecting elements in the DOM and modifying them.

Docs: Chrome, Firefox

2

One of the shortest ways would be just copy pasting the code below to the console.

var jquery = document.createElement('script'); 
jquery.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.head.appendChild(jquery);
0
1

If you're looking to do this for a userscript, I wrote this: http://userscripts.org/scripts/show/123588

It'll let you include jQuery, plus UI and any plugins you'd like. I'm using it on a site that has 1.5.1 and no UI; this script gives me 1.7.1 instead, plus UI, and no conflicts in Chrome or FF. I've not tested Opera myself, but others have told me it's worked there for them as well, so this ought to be pretty well a complete cross-browser userscript solution, if that's what you need to do this for.

1

Here is alternative code:

javascript:(function() {var url = '//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; var n=document.createElement('script');n.setAttribute('language','JavaScript');n.setAttribute('src',url+'?rand='+new Date().getTime());document.body.appendChild(n);})();

which can be pasted either directly in Console or create a new Bookmark page (in Chrome right-click on the Bookmark Bar, Add Page...) and paste this code as URL.

To test if that worked, see below.

Before:

$()
Uncaught TypeError: $ is not a function(…)

After:

$()
[]
1

If you want to use jQuery frequently from the console you can easily write a userscript. First, install Tampermonkey if you are on Chrome and Greasemonkey if you are on Firefox. Write a simple userscript with a use function like this:

var scripts = [];

function use(libname) {
    var src;
    if (scripts.indexOf(libname) == -1) {
        switch (libname.toLowerCase()) {
            case "jquery":
                src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
                break;
            case "angularjs":
                src = "//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js";
                break;
        }
    } else {
        console.log("Library already in use.");
        return;
    }
    if (src) {
        scripts.append(libname);
        var script = document.createElement("script");
        script.src = src;
        document.body.appendChild(scr);
    } else {
        console.log("Invalid Library.");
        return;
    }
}
1

Turnkey solution :

Put your code in yourCode_here function. And prevent HTML without HEAD tag.

(function(head) {
  var jq = document.createElement('script');
  jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js";
  ((head && head[0]) || document.firstChild).appendChild(jq);
})(document.getElementsByTagName('head'));

function jQueryReady() {
  if (window.jQuery) {
    jQuery.noConflict();
    yourCode_here(jQuery);
  } else {
    setTimeout(jQueryReady, 100);
  }
}

jQueryReady();

function yourCode_here($) {
  console.log("OK");
  $("body").html("<h1>Hello world !</h1>");
}

1

Here is a bookmark solution working in Chrome as of 2023.
This makes it so that you don't need to copy paste the injection script every time.

javascript:(function(){var script = document.createElement('script');script.src = "https://code.jquery.com/jquery-latest.min.js";document.getElementsByTagName('head')[0].appendChild(script);console.log("jQuery injected");})()

Set this in the URL field of your Chrome bookmark.

After clicking on the bookmark you can do something like this in the console:

$('element').length
0

intuitive one-liner

document.write(unescape('%3Cscript src="https://code.jquery.com/jquery-3.1.1.min.js"%3E%3C/script%3E’))

You can change the src address.
I referred to ReferenceError: Can't find variable: jQuery

0

Another option is just save the jQuery content in a snippet(chrome) and run (Right click+Run or CTRL+Enter) it on which ever site you want. It's not necessarily jQuery any javascript if you want to run it on demand. (for ex: SharePoint JSOM.. just save all JSOM files as snippets and run it in the required order)

-1

i have built upon the accepnted solution and made it better

var also_unconflict = typeof $ != "undefined";

var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

if(also_unconflict){
    setTimeout(function(){
        $=jQuery.noConflict();
        console.log('jquery loaded, use jQuery instead of $')
    }, 500)
}else{
    console.log('jquery loaded, you can use $');
}

i'm using this function in google chrome console snippet

Not the answer you're looking for? Browse other questions tagged or ask your own question.