Firefox DevTools: Automatically injecting jQuery - javascript

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.

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.

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.

Related

How can I define a property on the tab's main window object?

I'm trying to define the property jQuery on the window object from a content script with code in the setter. That way, when the actual jQuery object is defined, I can use it right away. I seem to be unable to get it right, though.
The target website is Outlook.com. That's the webmail version of Outlook.
I tried to put the code in the content script directly, but even if I put "all_frames": true in the content_scripts section of the manifest (so the code gets injected into every frame), it isn't working.
function afterInit(){
var _jQuery;
console.log('This gets logged');
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function(newValue) {
_jQuery = $ = newValue;
console.log('This is never logged!');
$(document.body).append($('<span>I want to use jQuery here</span>'));
}
});
}
afterInit();
I verified that window.jQuery is properly defined afterwards by the actual jQuery function/object, but my setter code is never executed.
I also tried it with message passing: I send a message with the code as a string to a background script, and use executeScript to execute it on the correct tab, but this also doesn't work.
chrome.runtime.sendMessage(
{action:'jQueryPreInit', value: '('+afterInit.toString()+')();'});
And in my background script:
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
switch (message.action){
case "jQueryPreInit": chrome.tabs.executeScript(sender.tab.id, {code: message.value});
}
});
If I put something else than the Object.defineProperty code in the executeScript code, that works fine. I only have problems defining the property.
(quotes are from a comment)
I want to use the jQuery provided by the page itself. I could try inserting the same jQuery file as Outlook does and hope it gets loaded from cache, but I'd rather just keep my extension as clean as possible, and use what is already available.
Your attempt at optimizing the extension is not workable / not recommended.
First off, you will not be able to use the page's code anyway because of the isolation between content script and webpage code. You cannot obtain a reference to page's own jQuery/$.
But let's for a moment suppose that you could. And then the site updates jQuery to another version, renames the jQuery object or stops using it entirely, which is outside your control. Result: your extension is broken. This is, partially, the rationale behind the isolation in the first place.
As a result of the context isolation, you are guaranteed there are no conflicts between your copy of jQuery and whatever runs on the site. So you don't need to worry about that: use your copy, and use the standard $ to access it.
Bundling a <100 KB file with your extension as a one-time download that makes sure code is available 100% of the time and with at worst disk-access latency is not making it less "clean", quite the opposite. It's a common practice and is enshrined in the docs.
Looking at your actual code, it executes in the content script context (regardless whether it's through manifest or executeScript), not in the page context. As such, no matter what the page does, $ will not be defined there.
I verified that window.jQuery is properly defined afterwards by the actual jQuery function/object [...]
I assume that you tried to execute window.jQuery in the console; by default, that executes it in the page context, not in your content script context (therefore, not reflecting the state of the content script context and not invoking your getter/setter). If you want to test your content script, you need to change top in the context drop-down above the console to your extension's context.
All that said, however,
When all is said and done, I want to use jQuery's ajaxSuccess function to execute code every time an e-mail is opened in the read pane.
Here we've got a problem. Since the content script code and webpage code are isolated, your code will never know about AJAX executing in the page's copy (not through ajaxSuccess, anyway).
Possible courses of action:
Rely on other methods to detect the event you want. Perhaps monitoring the DOM.
Inject some code into the page itself; the only way to do so is by injecting a <script> tag into the page from the content script. There, you can access the page's copy of jQuery, attach your listener and message your content script when something happens.
Rely on the background page to detect activity you need with webRequest API. This will likely intercept the AJAX calls, but will not give you the reply contents.
Final note: this may not be as simple as AJAX calls; perhaps the page maintains a WebSocket connection to get realtime push updates. Tapping into this is trickier.
Thanks to Xan, I found there are only two ways to do this.
The first is by adding a <script> element to the DOM containing the appropriate code. This is a pretty extensive StackOverflow answer on how to do that: https://stackoverflow.com/a/9517879/125938.
The second is using Javascript pseudo-URLs and the window.location object. By assigning window.location a bookmarklet-style URL containing Javascript, you also bypass certain security measures. In the content script, put:
location = 'javascript:(' + (function(){
var _jQuery;
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function(newValue) {
_jQuery = $ = newValue;
console.log('totally logged!');
$('<span>jQuery stuff here</span>');
}
});
}).toString().replace(/\n/g, ' ')+')();';
The reason I/you were originally failing to define it, was because both methods of code injection we were using, caused our code to be sandboxed into isolated worlds: https://developer.chrome.com/extensions/content_scripts#execution-environment. Meaning, they share the page's DOM and could communicate through it, but they can't access each other's window object directly.

Check where/which line or document a script gets called

I'm having a JavaScript debugging question. I would like to know, how it would be possible to find out in which file/line a new script is loaded and called. My website has several scripts which are appended via document.write(), and I would like to find a way to find the function call in all attached scripts of the website.
I would prefer either Firebug or Chrome Dev tools.
Thanks!
Neither Firebug nor the Firefox or the Chrome DevTools currently allow to debug code inserted via document.write(). I created bug 1122222 for the Firefox DevTools and issue 449269 for the Chrome DevTools requesting to be able to debug such scripts. As upcoming Firebug versions will be based on the Firefox DevTools, it will offer this feature once the Firefox bug is fixed, so there's no need to create a separate issue for it.
Until the above bugs are fixed you need to use another method to inject your script in order to be able to debug it within the browser.
Method 1: using eval()
You can use the eval() function to evaluate arbitrary code dynamically. Note that the eval() only evaluates JavaScript code, it must not be surrounded by any HTML.
Example:
eval("console.log('Hi!')");
Method 2: injecting a <script> tag
You can add a <script> tag to the page and then add contents to it.
Example:
var script = document.createElement("script");
script.textContent = "console.log('Hi!');";
document.body.appendChild(script);
Method 3: using new Function()
You can create a new function via the Function constructor.
Example:
(new Function("console.log('Hi!');"))();
Note that JavaScript won't be executed using innerHTML or insertAdjacentHTML() due to security reasons.

Debugging a jQuery plugin

Background
I have a snippet of javascript that sites on customer pages. When this script is executed, it loads necessary assets and scripts and then executes the main code.
One of the script's I'm loading is Twitter's bootstrap JS to create a modal window. It's implemented as a jQuery plugin, and adds '$.modal()' to a jquery object.
Problem
This works on all but one customer site. On this particular site, as I invoke $('#idOfWindow').modal();, the page throws a javascript error Object has no method 'modal'
I've verified that the bootstrap code is invoked, and $.fn.modal is called to setup the plugin, My hunch is that something is clobbering the jQuery object, but I'm not sure how to debug this.
Comments
I'm currently using Chrome's Developer Tools to Debug, and I have verified that the plugin is loaded and executed before it's ever called. The client site is using jQuery 1.7.2. I'm familiar with chrome tools, but I'm not a power user.
If you are right, that your original jQuery object is being overwritten somewhere, you should be able to restore it with jQuery.noConflict().
Demo: jsfiddle.net/KthZu
Edit: Some debugging tips:
To help in debugging, you can check the jQuery version in the console with this code:
$().jquery
Another potential debugging trick would be to store a reference to jQuery when you create you plugin.
$.fn.myPlugin = function(){};
window.jQueryWithMyPlugin = $;
Then, when debugging, you can plainly see if window.$ has been overwritten:
$ === jQueryWithMyPlugin
Generally for any widget type of code that is to be embedded externally, you'll want to wrap your code:
(function($){
$('#idOfWindow').modal();
})(jQuery);
I have, in the past had issues where multiple versions of jQuery (or jQuery & prototype) were loaded on the same page. Be sure that the version of jQuery you're adding $.fn.modal to is identical to the version that's being called. $().jquery can be used to access the specific version of jQuery in use.

Why am I able to use jQuery syntax in Chrome's JS console when current page doesn't have jQuery loaded?

I thought one has to have jQuery source loaded first in order to use $ to target elements. I was on a webpage that doesn't even include any scripts but somehow I was able to run $('body') inside the Javascript console and Chrome successfully returned its value.
Why didn't I get a syntax error like 'undefined token'? Thanks.
Before, Chrome had an alias to document.getElementById with the $ variable.
Recently (probably on Chrome 23 release), it has been changed to an alias to document.querySelector.
So your code is the equivalent of document.querySelector('body').
As already alluded to in the comments by #Shmiddty, it is likely due to a plugin you have installed...
You can find out by running developer tools, select 'Sources' and look at both the Sources and Content Scripts panes - is something suspiciously like jQuery in there somewhere?

How to help the debugger see my javascript, or how to best refactor my script to help make it debugger-friendly?

I have an ASP.NET MVC project that uses some simple AJAX functionality through jQuery's $.get method like so:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
});
The amount of content is relatively low here -- usually a single div with a short blurb of text. Sometimes, however, I am also injecting some javascript into the page. At some point when I dynamically include script into content that was itself dynamically added to the page, the script still runs, but it ceases to be available to the debugger. In VS2008, any breakpoints are ignored, and when I use the "debugger" statement, I get a messagebox saying that "no source code is available at this location." This fails both for the VS2008 debugger and the Firebug debugger in Firefox. I have tried both including the script inline in my dynamic content and also referencing a separate js file from this dynamic content -- both ways seemed to result in script that's unavailable to the debugger.
So, my question is twofold:
Is there any way to help the debugger recognize the existence of this script?
If not, what's the best way to include scripts that are used infrequently and in dynamically generated content in a way that is accessible to the debuggers?
I can not comment yet, but I can maybe help answer. As qwerty said, firefox console can be the way to go. I'd recommend going full bar and getting firebug. It hasn't ever missed code in my 3 years using it.
You could also change the way the injected javascript is added and see if that effects the debugger you're using. (I take it you're using Microsoft's IDE?).
In any case, I find the best way to inject javascript for IE is to put it as an appendChild in the head. In the case that isn't viable, the eval function (I hate using it as much as you do) can be used. Here is my AJAX IE fixer code I use. I use it for safari too since it has similar behavior. If you need that too just change the browser condition check (document.all for IE, Safari is navigator.userAgent.toLowerCase() == 'safari';).
function execajaxscripts(obj){
if(document.all){
var scripts = obj.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
eval(scripts[i].innerHTML);
}
}
}
I've never used jquery, I preferred prototype then dojo but... I take it that it would look something like this:
$.get(myUrl, null, function(result) {
$('#myselector').html(result);
execajaxscripts(result);
});
The one problem is, eval debug errors may not be caught since it creates another instance of the interpreter. But it is worth trying.. and otherwise. Use a different debugger :D
This might be a long shot, but I don't have access to IE right now to test.
Try naming the anonymous function, e.g.:
$.get(myUrl, null, function anon_temp1(result) {
$('#myselector').html(result);
});
I'm surprised firebug is not catching the 'debugger' statement. I've never had any problems no matter how complicated the JS including method was
If this is javascript embedded within dynmically generated HTML, I can see where that might be a problem since the debugger would not see it in the initial load. I am surprised that you could put it into a seperate .js file and the debugger still failed to see the function.
It seems you could define a function in a seperate static file, nominally "get_and_show" (or whatever, possibly nested in a namespace of sorts) with a parameter of myUrl, and then call the function from the HTML. Why won't that trip the breakpoint (did you try something like this -- the question is unclear as to whether the reference to the .js in the dynamic HTML was just a func call, or the actual script/load reference as well)? Be sure to first load the external script file from a "hard coded" reference in the HTML file? (view source on roboprogs.com/index.html -- loads .js files, then runs a text insertion func)
We use firebug for debug javascript, profile requests, throw logs, etc.
You can download from http://getfirebug.com/
If firebug don't show your javascript source, post some url to test your example case.
I hope I've been of any help!
If you add // # sourceURL=foo.js to the end of the script that you're injecting then it should show up in the list of scripts in firebug and webkit inspector.
jQuery could be patched to do this automatically, but the ticket was rejected.
Here's a related question: Is possible to debug dynamic loading JavaScript by some debugger like WebKit, FireBug or IE8 Developer Tool?

Categories