在 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

weixin_41568196
撒拉嘿哟木头 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 年多之前 回复
csdnceshi67
bug^君 add it to a script tag, either from cdn or locally. CDN is much simpler.
5 年多之前 回复
csdnceshi74
7*4 There is a chrome extension to do this - chrome.google.com/webstore/detail/script-injector/…
6 年多之前 回复
csdnceshi53
Lotus@ 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 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 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 年多之前 回复

19个回答

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.

csdnceshi51
旧行李 $=jQuery.noConflict(); Change the last line to this would be better.
2 年多之前 回复
weixin_41568196
撒拉嘿哟木头 The first comment should be the best answer, clean and straightforward for a quick and sweet jQuery function testing.
3 年多之前 回复
csdnceshi75
衫裤跑路 having jQuery.noConflict() in another script tag just below the first helped me
3 年多之前 回复
csdnceshi62
csdnceshi62 Note: this will not work if the target site has a Content Security Policy disallowing inclusion of scripts from that domain.
3 年多之前 回复
csdnceshi54
hurriedly% 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 年多之前 回复
csdnceshi58
Didn"t forge That code for console fails for me on latest Chrome: VM115:1 Uncaught ReferenceError: jQuery is not defined(…)
大约 4 年之前 回复
csdnceshi73
喵-见缝插针 It's 2016 and literally the only problem with that bookmarklet was a missing semicolon.
大约 4 年之前 回复
weixin_41568174
from.. How about: jq.onload = function(){ jQuery.noConflict() }; instead of having to wait for it to load to run the jQuery.noConflict()
4 年多之前 回复
csdnceshi63
elliott.david 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 年多之前 回复
csdnceshi59
ℙℕℤℝ is appending the script to the head tag the only way to add the jQuery object to the runtime?
5 年多之前 回复
weixin_41568208
北城已荒凉 Edit: wrap the jQuery no-conflict inside a timer: setTimeout(function(){jQuery.noConflict();}, 100)
接近 6 年之前 回复
csdnceshi56
lrony* to avoid conflict you should first check with jquery variable does exists or not...
大约 6 年之前 回复
csdnceshi74
7*4 I had a problem with this shippet, but the one here stackoverflow.com/a/8225200/497208 worked for me
7 年多之前 回复
csdnceshi77
狐狸.fox 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 年多之前 回复
csdnceshi77
狐狸.fox 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 年多之前 回复
csdnceshi77
狐狸.fox 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 年多之前 回复
csdnceshi78
程序go 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

csdnceshi62
csdnceshi62 Works perfectly @genesis! 2017, MS Edge browser.
3 年多之前 回复
csdnceshi64
游.程 If you get security message (on Facebook for instance), just copy/paste the jquery.js content in the javascript console.
接近 5 年之前 回复
weixin_41568134
MAO-EYE 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 年之前 回复

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

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

csdnceshi68
local-host It's always nice to be able to test and experiment with Jquery from the console, don't you think?
6 年多之前 回复
csdnceshi63
elliott.david :1 is not a pseudo selector. Maybe you want :first-child?
大约 7 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Florian. Your Answers and comments are very helpful. It doesn't seem like pseudoselectors are working for me. For instance, input#Address:1 doesn't seem to be working... Any insight?
大约 7 年之前 回复
csdnceshi54
hurriedly% You're not a rebel, it seems, instead, that you like to waste time typing more :)
7 年多之前 回复
csdnceshi57
perhaps? Still way more awkward to throw in stuff like animate().
接近 8 年之前 回复
csdnceshi76
斗士狗 [].slice.call( document.querySelectorAll('div.className .active') ).filter... but yeah the point stands: if you have modern browser dom is painless even without jQuery. :)
8 年多之前 回复
csdnceshi63
elliott.david Do you mean document.querySelectorAll('div.className .active').filter(function(index) {})? :p
8 年多之前 回复
csdnceshi65
larry*wei Thanks for the idea Florian. I agree that anyone using jQuery should also know javascript. Loading jQuery is a big time saver not just because it abstracts DOM inconsistencies. Its selector engine, sizzle, is far more powerful than any of the native javascript calls. Querying for something like $('div.className').children().hasClass('active').filter( function(index) { ... }); would be a nightmare in plain js.
8 年多之前 回复

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

csdnceshi78
程序go Hmm, you should use Firebug 2.0.8, which is the latest official version. Also the reason why include("jquery") doesn't work for you is definetely because you had created an alias before the version 1.11.4 as I mentioned. Just remove the includeAliases.json file (which contains include() aliases) in your firefox profile and that should work.
5 年多之前 回复
csdnceshi55
~Onlooker I have Firebug 1.12.8 and if I go to, let's say Google, while running include("jquery") in console gets me that error.
5 年多之前 回复
csdnceshi78
程序go Not since Firebug 1.11.4, which is by default (unless you have defined aliases before this release) : code.google.com/p/fbug/issues/detail?id=6133 (Note : I am the author of this feature :))
5 年多之前 回复
csdnceshi55
~Onlooker Actually it's include("http://code.jquery.com/jquery-latest.min.js", "jquery") for the first time use. If you just include("jquery"); you get the error Alias 'jquery' not found.. include("jquery"); is for reusing the same library on a different tab/domain.
5 年多之前 回复

Copy http://code.jquery.com/jquery-latest.min.js file content and paste it into console. Works perfect.

csdnceshi69
YaoRaoLov smooth answer.! was looking for your top comment as answer! great.
2 年多之前 回复
weixin_41568174
from.. I tried using a variety of the 3-line answers .. none of them would allow me to use jQuery or $ . Only this solution worked . And then since I'm not using the log console otherwise too much these days - it's always in my command history, so after the first time I copied in the content - now, only need to hit up-arrow and then enter. Very cool - thank you
3 年多之前 回复
csdnceshi76
斗士狗 First check if there is a $ variable. If it's not jQuery one should probably let go of jQuery hold on $ var. After invoking above script type: $.noConflict()
7 年多之前 回复
csdnceshi76
斗士狗 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 ....
7 年多之前 回复

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)})
csdnceshi77
狐狸.fox 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 年之前 回复
csdnceshi78
程序go 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 年之前 回复

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.

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_41568174
from.. 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 年多之前 回复
csdnceshi76
斗士狗 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 年之前 回复

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

csdnceshi58
Didn"t forge 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 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 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 年多之前 回复
weixin_41568127
?yb? +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 年之前 回复
共19条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐