I run in Chome devtools next code
(function() {
var a = 5;
debugger; // when I stop here I evaluate `a = 9`
console.log(a);
})(); // and got 5
but if I use
(function() {
var a = { a: 5 };
debugger; // when I stop here I evaluate `a.a = 9`
console.log(a.a);
})(); // and got 9
Why?
PS
also why it doesn't work in FF / Safari (it even didn't stop in debugger line )
This is behavior is simply a bug, and will be fixed in an upcoming release.
If you want a "why" deeper than that, you'll need to know a lot about Chrome's debugger and JavaScript implementation. According to the diff of one file in the fix, the debugger formerly used a context_builder.native_context but now it uses a context_builder.evaluation_context. Apparently the native_context created by the old debugger code had trouble resolving (or not treating as read-only) local-scope variables. If you really wanted more, you could contact the author of the fix.
As for why the debugger does not appear in Firefox: it will appear if you are running code from a <script> and have your dev tools open. When running code from the console, it appears that you must have the debugger tab open specifically. Obviously, this is not possible if you have the console open to type in your code, but you can wrap it in setTimeout and quickly switch to the Debugger tab:
setTimeout(function() { debugger; }, 5000)
It is a matter of how the variables are used. Objects are used by reference. So changing a.a will effectively change the value at the proper memory address. Though, changing a itself in any of your test version won't do anything because a new memory address is created for the variable evaluated in the console.
For FireFox not breaking at debugger line, it states in this page (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) : "If no debugging functionality is available, this statement has no effect.". So, you have to ensure FireBug is installed I presume.
Related
Can I set a breakpoint on a standard JavaScript function? For example, can I pause the debugger every time context.beginPath() is called? Or every time that String.replace() is called?
UPDATE: What I meant by standard JavaScript function is functions built-in into the JavaScript engines.
Yes you can do this by overriding the original functionality by performing the following two steps:
Make a copy(reference really) of the original function:
mylog = console.log;
Override the original with your copy inserting the debugger statement:
console.log = function(){
debugger;
mylog.apply(this, arguments);
}
Now when called console.log will perform a breakpoint. (Note you'll have to handle different function arguments differently depending on the function be overriden)
Here is another example using an instance methods, for example String.prototype.replace:
let originalFunction = String.prototype.replace;
String.prototype.replace = function(...args) {
debugger;
return originalFunction.call(this, ...args);
}
console.log('foo bar baz'.replace('bar', 'BAR'));
Are you looking for the debugger statement?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger
There are 3 ways to set up a breakpoint and debug the code.
1. Chrome dev-tools / Firebug:
Using Chrome developer tools or firebug to locate the line of
JavaScript, then set the breakpoint with the mouse. In chrome, you
should first open(ctrl+shirt+I) to open developer tools.
Select the script tab or click on (ctrl+P) to open then desired file.
Search the line on which you wanted to set a breakpoint and set a
breakpoint.
Whenever you execute your code next time in a browser, the breakpoint
is fired. In watch section, you may see every expression, all
variables in scope, and the call stack too.
2. Debugger
Using debugger statement, it fires every time and it helps when it
hard to find the execution of code.
debugger;
3. Webstorm IDE / Visual Studio Code
Webstorm IDE/Visual Studio Code have the facility to debug a code from
IDE.
Javascript is a really flexible language and probably following the way to override existing javascript and debug method then please use following a way of debugging.
var fnSetAttribute = Element.prototype.setAttribute;
Element.prototype.setAttribute = function(name, value) {
if (name == 'clone') {
debugger; /* break if script sets the 'clone' attribute */
}
fnSetAttribute.call(this,name,value); /* call original function to
ensure those other attributes are set correctly */
};
For more reference please review https://alistapart.com/article/advanced-debugging-with-javascript
Works in Google Chrome Console:
debug(console.log) // sets a breakpoint on "console.log" builtin
console.log("Hello")
It shows the Sources pane and says
🛈 Paused on debugged function
I wrote the following code for debugging puposes:
(function () {
"use strict";
// The initialize function is run each time the page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
// Use this to check whether the API is supported in the Word client.
if (Office.context.requirements.isSetSupported('WordApi', 1.1)) {
// Do something that is only available via the new APIs
Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, onSelectionChanged);
}
else {
// Just letting you know that this code will not work with your version of Word.
$('#status').html('This code requires WordApi 1.1 or greater.');
}
});
};
var c = 1;
function onSelectionChanged(eventArgs) {
c++;
$('#status').html('onSelectionChanged() call '+c+);
}
})();
This code only sometimes reacts to changes. Sometimes reeaaly slow. Sometimes (I guess, if it is too slow and there have been multiple changes in between, it does not recognize them und prints onSelectionChanged() call 4 after a while, even though, there have been many more changes.
Other times, if I close Word, and open it again, it just works as a charm. Then I close it and open it again, and again, it fails - It is completely inconsistant. Thereby this feature is effectively not usable.
I tested this on different machines, different versions of Windows and it occures independend of the utilization of the system.
Any ideas?
Unfortunately I was not able to repro your issue. The event works quite consistently.
Its not related but is there a specific reason why you are checking the 1.1 requirement set? This event was shipped on the first release of the API so that's not needed.
If you can provide your build number and a sample document and video of whats going on we could investigate in more detail.
thanks!
I have a small piece of code for a template project I'm working on. There are three separate buttons, that point to three separate locations. In order to make it easier for content providers, I have these buttons calling minimal routines to load the next page.
The code is as follows:
/* navigation functions here for clarity and ease of editing if needed */
prevURL = 'ch0-2.html';
nextURL = 'ch2-1.html';
manURL = 'ch1-2.html';
function prevPage() {
window.location = prevURL;
}
function nextPage() {
window.location = nextURL;
}
function goManager() {
window.location = manURL;
}
This works perfectly in Firefox and Chrome, but seems to fail in Internet Explorer.
I open up the developer tools in IE (F12) and am presented with the message:
SCRIPT5009: 'manURL' is undefined
The location information (line 43, character 13) points to the "window.location = manURL" part of the code.
However, once the developer tools are open, if I hit F5 to reload the page, the button works without error until I close IE and reopen it, where it once again fails to respond and gives the same "undefined" error.
I'm baffled. Anyone have any ideas?
UPDATE
I know the variable declaration is poor, and that I can use window.location.href instead. What is relevant here is that the other two pieces of code, which are identical in all of these significant ways, work perfectly either way.
epascarello has put me on the right track. by removing all console.log commands, everything starts working. I'm just wondering why this happens, and would like to be able to give epascarello credit for helping me.
IE does not have console commands when the developer window is not open. So if you have them in there the code will not run. It will error out.
You can either comment out the lines or add in some code that adds what is missing.
if (typeof console === "undefined") {
console = {
log : function(){},
info : function(){},
error : function(){}
//add any others you are using
}
}
Try setting
window.location.href
instead of just window.location.
Source:
http://www.webdeveloper.com/forum/showthread.php?105181-Difference-between-window.location-and-window.location.href
Always define variables before using them ,being explicit (expressing the intention) is a good practice,
so define your variables like this,
var prevURL = 'http://google.com';
var nextURL = 'http://msn.com';
var manURL = 'http://stackoverflow.com';
You can try using
window.location.href
refer to this post for difference
Suggestion:
Make a jsfiddle.net for us so we could guide you easily
Is it possible to add messages to the built-in error console of Firefox from JavaScript code running in web pages?
I know that I there's Firebug, which provides a console object and its own error console, but I was looking for a quick fix earlier on and couldn't find anything.
I guess it might not be possible at all, to prevent malicious web pages from spamming the log?
If you define a global function that checks for the existence of window.console, you can use Firebug for tracing and still plays nice with other browsers and/or if you turn Firebug's console tracing off:
debug = function (log_txt) {
if (typeof window.console != 'undefined') {
console.log(log_txt);
}
}
debug("foo!");
You cannot write to the console directly from untrusted JavaScript (e.g. scripts coming from a page). However, even if installing Firebug does not appeal to you, I'd recommend checking out Firebug Lite, which requires no installation into the browser (nor, in fact, does it even require Firefox). It's a script which you can include into any web page (even dynamically), which will give you some basic Firebug functionality (such as console.log()).
Yes, you can =P
function log(param){
setTimeout(function(){
throw new Error("Debug: " + param)
},0)
}
//Simple Test:
alert(1)
log('This is my message to the error log -_-')
alert(2)
log('I can do this forever, does not break')
alert(3)
Update to a real function
This is a simple hack, just for fun.
window.console is undefined in Firefox 4 beta 6 even if Firebug 1.6X.0b1 is enabled and open, probably because of privilege issues that others discuss. However, Firefox 4 has a new Tools > Web Console, and if this is open you have a window.console object and untrusted JavaScript code on the page can use console.log(). The Web Console is in flux (see https://wiki.mozilla.org/Firefox/Projects/Console), you may need to change settings named devtools.* in about:config , YMMV.
I would just install Firebug and use console.log. If you can't do that, though, you can always throw an error:
throw "foobar";
throw new Error("bazquux");
Of course, this will break you out of the code that you're currently executing, so you can't use it for detailed logging, but if you can work around that I think it's the only way to get something logged out of the box.
AFAIK, it is not possible. But if you are interested in how extensions in Firefox interact with the error console, check this out.
This function does not require any extension nor library. However it grants full privileges to the relevant website. No worries since you are the one developing it, right?
// Define mylog() function to log to Firefox' error console if such a
// thing exists
function defineMyLog()
{
// Provide a useless but harmless fallback
mylog = function(msg) { };
// return; // disable in production
if (typeof(netscape) === "undefined") {
// alert("Logging implemented only for Firefox");
return;
}
// The initial auth popup can be avoided by pre-setting some magic user_pref
// ( "capability.principal.codebase.p0.granted", "UniversalXPConnect"), etc.
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) { // User has denied privileges
// alert(e.name + ": " + e.message);
return;
}
ffconsoleService = Components.classes["#mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService);
mylog = function (msg)
{
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
ffconsoleService.logStringMessage(new Date().toLocaleTimeString() + ": " + msg);
}
mylog("Firefox logging function has been defined");
// window.open("javascript:"); // this URL does not work anymore?
}
If you're interested, check out a script I wrote -- it's a "cheap" Firebug replacement that doesn't interfere with any normal console (like Safari or Chrome) but does extend it with almost all the Firebug methods:
http://code.google.com/p/glentilities/
Look under the hood and you'll see what I mean by "cheap". :-)
Combine it with YUI or json.org's JSON serializers to sorta replicate console.dir.
Firebug and Firebug Lite are definitely nicer GUIs, but I use my home-grown one all the time to retain logging safely even for production code -- without constant commenting & un-commenting,
I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.
The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. Everything works fine in Firefox, so I don't have the delights of Firebug and friends to assist in troubleshooting.
Are there any standard causes for this? I'm guessing this is probably an Internet Explorer 7 bug or something quite obscure, and my Google-fu is bringing me little joy currently. I can find lots of people who have run into this before, but I can't seem to find how they solved it.
I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.
http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/
The quick summary is: recursion that passes through the host global object is limited to a stack depth of 13. In other words, if the reference your function call is using (not necessarily the function itself) was defined with some form window.foo = function, then recursing through foo is limited to a depth of 13.
Aha!
I had an OnError() event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...
For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.
You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.
I've found that it is one of few ways to diagnose some of those IE specific issues.
I had this problem, and I solved it. There was an attribute in the <%# Page tag named MaintainScrollPositionOnPostback and after removing it, the error disapeared.
I added it before to prevent scrolling after each postback.
If you came here because you had the problem inside your selenium tests:
IE doesn't like By.id("xyz"). Use By.name, xpath, or whatever instead.
Also having smartNavigation="true" causes this"
I set up a default project and found out the following:
The problem is the combination of smartNavigation and maintainScrollPositionOnPostBack. The error only occurs when both are set to true.
In my case, the error was produced by:
<pages smartNavigation="true" maintainScrollPositionOnPostBack="true" />
Any other combination works fine.
Can anybody confirm this?
Internet Options
Tools
Internet options
Advanced
Navigation section
Click > Disable script debugging
display a notification about every script error
sign in
You will smile !
My was "at line 1" instead but...
I got this problem when using jQuery's .clone method. I replaced these by using making jQuery objects from the html string: $($(selector).html()).
I have reproduced the same error on IE8. One of the text boxes has some event handlers to replace not valid data.
$('.numbersonly').on("keyup input propertychange", function () {
//code
});
The error message was shown on entering data to this text box. We removed event "propertychange" from the code above and now it works correctly.
P.S. maybe it will help somebody
I don't know what to tell you, but the same problem occured with jQuery table sorting and SEARCH.
When there is nothing left in the table, where you are searching a string for example, you get this error too. Even in Google Analytics this error occurs often.
In my case I had two functions a() and b(). First was calling second and second was calling first one:
var i = 0;
function a() { b(); }
function b() {
i++;
if (i < 30) {
a();
}
}
a();
I resolved this using setTimeout:
var i = 0;
function a() { b(); }
function b() {
i++;
if (i < 30) {
setTimeout( function() {
a();
}, 0);
}
}
a();
This is problem with Java and Flash Player. Install the latest Java and Flash Player, and the problem will be resolved. If not, then install Mozilla Firefox, it will auto install the updates required.