Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox DevTools: Automatically injecting jQuery

I'm doing quite a bit of work in the developer tools, and like to use jQuery in the console to run code snippets. To inject jQuery into the page (and the console), I'm pasting this into the devtools console:

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

Is there a way to inject jQuery automatically into the developer tools console? Ideally, without affecting window.$ or window.jQuery for the current page.

like image 977
silverwind Avatar asked Oct 07 '14 22:10

silverwind


2 Answers

The Developer Toolbar has an inject command that will allow you to inject a script into the current page a bit more easily. It supports commonly used libraries like jQuery and underscore. For more, see the docs I linked to.

If you wanted to always do this, you could create an add-on similar to dotjs - the main difference is that you would need to expose the jQuery object into the page's actual DOM, a content script isn't good enough. You should probably also always try to detect an existing jQuery? I'm not quite sure what you mean by 'without affecting window.$ or window.jQuery for the current page' - the current scope of the console by default is the current page. This is only different if you are debugging and are stopped at a breakpoint inside some other scope.

like image 144
therealjeffg Avatar answered Sep 25 '22 09:09

therealjeffg


You can copy/paste the below code into the console and jQuery will be available to you in DevTools

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

// ... You might need to also run
jQuery.noConflict();

You might immediately see an error: Uncaught ReferenceError: jQuery is not defined. Ignore it - DevTools is pulling your leg. (Google's weak attempt at humor, maybe...)

Then, in DevTools console, test it:
$('div').length; //press Enter

If you get an error, try it this way:
jQuery('div').length

Hopefully, the first will work - but sometimes you'll need to use the second method.

like image 42
cssyphus Avatar answered Sep 22 '22 09:09

cssyphus