How to debug javascript in Visual Studio 2013 - javascript

We are trying to build a Windows 8 native application using JavaScript. We are using jQuery to dynamically load the javascripts files, and all the javascript files are stored inside of the app. When I try to debug the javascript, the breakpoint can't hit, saying "The breakpoint will not currently be hit....", but in the Solution Explorer, there is a Script Documents project, there is a file called "script block", which contains all the javascripts which are loaded from jQuery. I can debug from there after I disable the "Enable Just My Code", but it's difficult to find the right place to put breakpoint, since this file is huge...
Actually all the javascript files are having sourcemap attribute, for example: //# sourceURL=ms-appx://d664ef20-6ac8-11e4-ab78-2f4dc8b50d53/www/resources/abc.js
It is working fine with all the browsers, IE, Safari, Firefox and Chrome. But Visual Studio seems not be able to recognize them.
Anyone who has the same issue?
Regards,
Xiaojun

I expect you are doing this, which evals the contents as a string, causing the string to be added to the "eval code" file under Script Documents. Note, you can still set breakpoints, you just have to do it from the "eval code" document.
// eval via AJAX -- adds to the "eval code" document
$.ajax("./js/fileToAdd.js").done(function (data) {
window.eval(data);
});
If you load the file via a script tag, the script file is loaded separately and breakpoints bind as expected because the contents are tied to the file and not a string. Here's how:
// Add <script> tag to head -- Causes script file to be loaded/displayed individually
var scriptTag = document.createElement("script");
scriptTag.src = "./js/fileToAdd.js"
document.head.appendChild(scriptTag);

Related

Unable to get proper Ace Editor Text in Google Chrome Extension

I am making Google Chrome Extension which gets the text from ACE Editor. But as soon as I create ACE object, formatting is lost and I am not able to get the Java code with indentation. The result also contains many unwanted characters.
I have used following code.
var editor = ace.edit('editor');
var code = editor.getValue();
Before my code is executed
After my code is executed
But when I run same code from developer console, it works fine.
Please suggest what is wrong or any other way to get full code with formatting using DOM element?
This happens because code in chrome extension doesn't have access to the code running in the page.
When you call ace.edit on existing editor env property of the element and creates a new editor instead.
As a workaround you can create a content script which will run in the page context, and communicate with the rest of extensions using events or postMessage. See https://stackoverflow.com/a/13292994/1743328 for more details

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.

no line breaks in firebug when dynamically loading script with jQuery

When I dynamically load a script with jquery
...
options = {
dataType: "script",
cache: true,
url: "...appContr.js"
}
return jQuery.ajax(options);
...
and I debug the script with firebug, this script has the name "1" and everything is in
one line (or in a few lines). I cannot use this for debugging.
I use Firefox 10.0.2 and Firebug 1.9.1.
When I use LAB.js
$LAB.script("...appContr.js").wait(function() {
...
});
or require.js
The file has its line breaks and the name of the script is "appContr".
How can I change the jQuery command in order to get the same result?
Thanks a lot in advance
EDIT:
Thank you, Headshota, for your answer, but this does not help.
Besides, getscript does not cache the contents, and this is important for me.
EDIT:
Thank you, Marlin, for your answer:
The whole thing works without firebug enhancements when I load the script with lab.js or require.js, the problem is only with jquery script loading.
In firebug I have the tabs console, html, css, script, dom and network.
If I go - after jquery script loading - to script and view the script, there are no line breaks in the code.
But when I go to the "tab" console, I have one entry for the get request. When I click
"answer" in this get request, the script contains the line breaks. But this does not help me because in the "script" tag the line breaks are missing.
dataType: script tells jQuery.ajax() to interpret the response as JavaScript and evaluate it.
"script": Evaluates the response as JavaScript and returns it as plain
text.
An evaluated code basically has no file, line number and probably no white space. If you try to debug it in FireBug, it will probably tell you that it is "eval()ed" code.
JavaScript loaders such as LABjs work by injecting a <script src> tag in your document; it is easier for FireBug to debug because the JavaScript filename, file content and line numbers are all available.
I am not certain how to get the script's name right in firebug, but as to your other dilemmas there are a couple Firebug extensions you should consider
JS Deminifier 1.0.7 by Ben Murphy: This will expand your javascript into very readable code (but can lead to breaks if the javascript has been incredibly minified but that doesnt sound like it'll happen in your case). Just make sure that you turn on your addon bar which shows up below firebug and JSD is set to on (in the bottom left).
Another Good Option for Javascript debugging in Firebug...
FireRainbow 1.5 by BinaryAge: This provides javascript viewed in firebug with very helpful syntax highlighting.
Hope these tools alleviate your issues.

Visual Studio 2008 jQuery IntelliSense sporadically fails, restarting VS fixes

Right off the bat, this is not your standard "I can't get javascript IntelliSense to work in Visual Studio." For the record:
I'm using Visual Studio 2008
I have installed SP 1
I have installed the hotfix for -vsdoc.js documentation files KB958502
I am developing a suite of interrelated jQuery plugins to be packaged as resources in a class library. So within a directory, I have (as an example):
jquery-vsdoc.js
core.js
plug1.js
plug2.js
In core.js, I have the following at the top of the file:
/// <reference path="jquery-vsdoc.js" />
Then in each of the plug#.js, I have:
/// <reference path="jquery-vsdoc.js" />
/// <reference path="core.js" />
The IntelliSense works initially, even including the additions from core.js when working in the plugins. However, sometimes the slightest change, even adding and removing a space from the reference XML tags, or pressing Ctrl-Shift-J, results in the dreaded "Error updating JScript IntelliSense: Client-side script IntelliSense information was not generated due to an error in an external script reference." Except it was working with that external script reference just a second ago!
For the jquery-vsdoc.js, I am using Comment Version 1.3.2b (that's what it says in the file) from http://jqueryjs.googlecode.com/files/jquery-1.3.2-vsdoc2.js. I am omitting the version number from the file so that I don't have to change a bunch of references when it's inevitably updated.
So what could be the problem? Restarting Visual Studio is proving to be a horribly inelegant (and time-consuming) workaround.
Have you tried increasing the IntelliSense timeout?
By default, every IntelliSense request
is only allowed 15s to execute. This
is to prevent IntelliSense from
scripts with infinite loops. If you
have a large script or slower machine,
it may make sense to increase the
timeout limit. The timeout value
store within following registry keys
(depending on if your are using
Express or the full product). The
value is in milliseconds so choose
something greater than 15000.
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\HTML
Editor\JsFailsafeTimeout
HKEY_CURRENT_USER\Software\Microsoft\VWDExpress\9.0\HTML
Editor\JsFailsafeTimeout
Does closing and opening the file reset the state?
Open the task manager and watch the processes. Do you see a process called "typelibbuilder.exe" get started when you press Ctrl-Shift-J?
I'm trying to image what sort of problems might require a restart of VS. The processing of references (to which that message pertains) is done in a new and separate process every time you press Ctrl-Shift-J (unless processing has been disabled in which case you would see a different message). It almost sounds like the communication between VS and typelibbuilder or some other necessary component is failing.
In SP1, you shouldn't need to reference the "-vsdoc" files directly. If you reference "foo.js" and there is a "foo-vsdoc.js" file next to it, then VS will use the vsdoc version to generate intellisense. I doubt that is related to your problem though.
I know this isn't much consolation, but we've drastically improved performance and reliability of Javascript Intellisense in Visual Studio 2010. Beta1 is currently available to MSDN subscribers (although it is beta and there are still some bugs in it).
If you can get reliable repro steps, you could also file a bug report at http://connect.microsoft.com/.
I dont know if this will help you, but I've encountered the following bug in VS 2008 JS intellisense:
When adding jQuery as a reference in an external file, and then I update JS I get:
'XmlHttpRequest is undefined' on the line:
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
It seems like the JS intellisense engine is actually executing some of the jQuery code (more than likely to inspect it so it can provide some more information about it). However it looks like window.ActiveXObject is null to the engine, and so it falls into the 'new XMLHttpRequest()' block - which also fails.
I hacked a workaround that breaks all browsers except IE - so not a good solution. My fix changes the following:
xhr: function()
{
// hack to fix VS 2008 intellisense... note this breaks any browser
// except IE
var objXhr = { open: function() { },
setRequestHeader: function() { }
};
return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : objXhr;
},
Now my intellisense works.
You may want to disable JavaScript intellisense in Visual Studio.
When SP1 is installed you can disable JavaScript intellisense.
Go to Tools, Options...
The Options dialog will show up.
Navigate to the following node in the left hand sided panel:
Text Editor :: JScript :: General
Disable the following options (in the group Statement Completion):
* Auto list members
* Parameter information

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