在 JavaScript 控制台中包含 jQuery

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?

转载于:https://stackoverflow.com/questions/7474354/include-jquery-in-the-javascript-console

csdnceshi68
local-host 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/….
4 年多之前 回复
csdnceshi80
胖鸭 add it to a script tag, either from cdn or locally. CDN is much simpler.
5 年多之前 回复
weixin_41568134
MAO-EYE There is a chrome extension to do this - chrome.google.com/webstore/detail/script-injector/…
6 年多之前 回复
csdnceshi79
python小菜 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.
接近 7 年之前 回复
csdnceshi58
Didn"t forge For more of an automated approach you can use a userscript to include it. Seriously this would be like a 5 line userscript :P
8 年多之前 回复

18个回答

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/2.1.4/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.

csdnceshi56
lrony* $=jQuery.noConflict(); Change the last line to this would be better.
2 年多之前 回复
csdnceshi74
7*4 The first comment should be the best answer, clean and straightforward for a quick and sweet jQuery function testing.
3 年多之前 回复
csdnceshi77
狐狸.fox having jQuery.noConflict() in another script tag just below the first helped me
3 年多之前 回复
weixin_41568208
北城已荒凉 Note: this will not work if the target site has a Content Security Policy disallowing inclusion of scripts from that domain.
3 年多之前 回复
csdnceshi57
perhaps? I was going to try it in MS Edge (have to use it for TurboTax, because Chrome doesn't support for some reason). Then I found out in this article that the only way to use a bookmarklet is through 3rd party tools. howtogeek.com/231775/…
3 年多之前 回复
weixin_41568196
撒拉嘿哟木头 That code for console fails for me on latest Chrome: VM115:1 Uncaught ReferenceError: jQuery is not defined(…)
大约 4 年之前 回复
csdnceshi51
旧行李 It's 2016 and literally the only problem with that bookmarklet was a missing semicolon.
4 年多之前 回复
weixin_41568110
七度&光 How about: jq.onload = function(){ jQuery.noConflict() }; instead of having to wait for it to load to run the jQuery.noConflict()
4 年多之前 回复
csdnceshi73
喵-见缝插针 I want to use this to include jQuery on sites that don't have it, but couldn't I just wrap the code above in if(typeof($) === 'undefined') to avoid conflicts?
5 年多之前 回复
weixin_41568134
MAO-EYE Your code says that it cannot read the property 'noConflict' of undefined. Sorry this doesn't work.
5 年多之前 回复
csdnceshi71
Memor.の is appending the script to the head tag the only way to add the jQuery object to the runtime?
5 年多之前 回复
csdnceshi52
妄徒之命 Edit: wrap the jQuery no-conflict inside a timer: setTimeout(function(){jQuery.noConflict();}, 100)
接近 6 年之前 回复
csdnceshi60
℡Wang Yan to avoid conflict you should first check with jquery variable does exists or not...
6 年多之前 回复
csdnceshi76
斗士狗 I had a problem with this shippet, but the one here stackoverflow.com/a/8225200/497208 worked for me
7 年多之前 回复
csdnceshi75
衫裤跑路 seems legit.
7 年多之前 回复
csdnceshi67
bug^君 they're sorted on the key name in chrome_switches.cc & base_switches.cc - and everywhere they're documented, they're just enumerated out in that order, aside from a few conditional groups, for say Windows, OSX, Android, Chrome OS ..
7 年多之前 回复
csdnceshi75
衫裤跑路 I am enjoying your sense of humour. Hopefully the overlords are listening, so they can push that DIY b-tree channel. I also particularly like how all the experiments are categorized so usefully. I think they sorted on hash value.
7 年多之前 回复
csdnceshi67
bug^君 by the way, you'll find them in the sources panel, and to save them (you must explicitly save them) you only have Ctrl+S or CMD+S there's no menu / icon for saving, not even a context menu. See.. it's easy! - mind you this from the company that brought you "tap the build number 8 times to get dev mode" on the Nexus Tablet, at least they don't make you build a b-tree from scratch, and submit your solution for review, before they let you use snippets... that's next version.
7 年多之前 回复
csdnceshi67
bug^君 note that in the latest builds, you have to enable developer experiments in chrome:flags, restart and then open the console settings, choose experiments, and then select snippets... then restart. They don't want to make this shit easy do they!?
7 年多之前 回复
csdnceshi67
bug^君 - AKAIK there's a developer snippets feature in the works, check your chrome:flags and see if it's there, you'll need to switch it on.
7 年多之前 回复
csdnceshi75
衫裤跑路 Now I just need a chrome console hot key for this ^^. I KEEP using this snippet, and surfing back to here to get it.
7 年多之前 回复
csdnceshi55
~Onlooker 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.
接近 8 年之前 回复

Run this in your console

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

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

csdnceshi73
喵-见缝插针 Works perfectly @genesis! 2017, MS Edge browser.
3 年多之前 回复
csdnceshi74
7*4 If you get security message (on Facebook for instance), just copy/paste the jquery.js content in the javascript console.
大约 5 年之前 回复
csdnceshi65
larry*wei This worked perfectly, thanks! (For the record, I was getting "Uncaught TypeError: $ is not a function", and after running this, I was able to utilize and chain $-selector functions normally.)
5 年多之前 回复

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.

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.

csdnceshi75
衫裤跑路 works great in chrome 57 (march 2017)
3 年多之前 回复

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);

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

csdnceshi64
游.程 Maybe the website on that you are trying to use this sends a custom Content-Security-Policy header.
5 年多之前 回复
csdnceshi62
csdnceshi62 I ran this, and still got "Uncaught TypeError: $ is not a function"...
5 年多之前 回复
csdnceshi64
游.程 I updated the code.
6 年多之前 回复
weixin_41568126
乱世@小熊 This works well although the url for .js file has to updated.
6 年多之前 回复

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

weixin_41568183
零零乙 The jQuery.noConflict(); made it appear to not work on a random site I was testing this on. Turned out they already had jQuery, but their jQuery doesn't have the $ shortcut for some reason. Screenshot: prntscr.com/bdcpdh.
4 年多之前 回复
csdnceshi55
~Onlooker 2 improvements: 1) it takes time for the script to be loaded, so the if(jQuery)... will almost always fail. I suggest to add a setTimeout to delay the load; 2) don't use the jquery-latest, it's not really the latest and it's use is deprecated (look at this blog.jquery.com/2014/07/03/dont-use-jquery-latest-js)
大约 6 年之前 回复

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();

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

weixin_41568131
10.24 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.
2 年多之前 回复
csdnceshi71
Memor.の 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
2 年多之前 回复
csdnceshi63
elliott.david +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 =).
大约 9 年之前 回复

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)})
csdnceshi71
Memor.の That did not work for me. But having two evals in the last block did work fetch('http://code.jquery.com/jquery-latest.min.js').then(response => response.text()).then(text => { eval(text); eval(text) }). This is a definite improvement over having to do it twice.
大约 4 年之前 回复
weixin_41568110
七度&光 Maybe because it runs asynchronously, this is how the JS callbacks and promises works. So to be sure that script is executed, you have to run your own code inside the 'then' callback of the fetch promise: fetch('http://code.jquery.com/jquery-latest.min.js').then(response => response.text()).then(text => { eval(text); console.log($) }). Hope this helps you.
大约 4 年之前 回复
共18条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐