How to check if 'debugger;' keyword exists? - javascript

Sometimes some developers forgot to remove debugger; in javascript code, and it produce javascript error on IE.
How can you check (like for the console: if(window.console){console.log('foo');}) if a debugger exists?
BTW: I don't want to detect if the browser is IE, I want a generic method if possible
Thanks,

You cannot.
The best solution would be adding a hook to your version control system to prevent code containing debugger; statements from being committed/pushed.
Asking your devs to search for debugger; or at least have a careful look at the diff before committing is also a solution - but not as effective as hard-rejecting in the VCS.

You could attempt to compile a function that declares debugger as a local variable. If debugger is reserved as a keyword, the JS engine will throw an error which you can catch.
var debuggerIsKeyword = false;
try {
new Function("var debugger;");
} catch(e) {
debuggerIsKeyword = true;
}
However I'm not sure that knowing whether a keyword exists or not is actually helpful.

Maybe the safest approach is to have a global include file for all your projects that stubs out the debugger if it doesn't exist:
if (typeof debugger == 'undefined') {
window.debugger = null;
}
That way calls to debugger just become a reference to null. which is harmless. Seems like a better approach than expecting forgetful developers to wrap each debugger call in an if statement.
The same approach works for console.log, etc.
EDIT: As AndrewF points out, debugger is actually a keyword, not a global, so this won't work. The same effect can be achieved using the following without throwing an error:
window['debugger'] = null;

Haven't tried it for lack of an IE, but this should work:
if (typeof console !== 'undefined') {
console.log("logging enabled");
}

Related

ie8 Expected Identifier error - Angular

My app is running in almost all browsers but when I use ie8 Expected Identifier happened.
$scope.delete = function (index) {
$scope.recipelists.splice(index, 1);
localStorage.setItem('markedRecipes', JSON.stringify($scope.recipelists))
if ($scope.recipelists == 0) {
$modalInstance.dismiss('cancel');
}
}
this is where ie8's console direct me when the error shows.
I don't know what's wrong with this.
Thanks!
IE8 doesn't support reserved words as literal object properties. Use
$scope['delete']
instead.
As per my understanding IE8 give storage to only valid domains. Try placing your example in some Web-server it should resolve the issue.
I faced the same issue when I tested it as an individual file but when i placed it in a server(Tomcat in my case) it just worked fine.
Source:-https://stackoverflow.com/a/12776794/1632286

use of globalstorage is deprecated. please use localstorage instead

I got this message when doing some javascript programming, and after some google searches, I have no idea what it means, or how i cause this error. I'm including the code below, can someone explain it to me or point me to a resource on how to fix it or what is happening at all? The weird thing is that I have other code just like this part in my program, and it never gives me errors about them, so i'm really confused. Also, I only get this error to display with firebug running, else wise it just doesn't work and no error message is displayed. I also tried it in Chrome, and had the same issues, no error message but the code doesn't work.
foundTextFn = function(){
console.log('fire');
if (foundTextArrayPosition != foundTextArray.length){
writeText(foundTextArray[foundTextArrayPosition],"happy");
foundTextArrayPosition += 1;
}
foundTextFnTimer=setTimeout("foundTextFn()",4000);
}
Here is another of my methods, it is basically the same thing, but it works fine. And if it matters, all of these variables are global variables declared at the start of my file as var foundTextArrayPosition = 0; for example.
awayFn = function(){
if (awayArrayPosition != awayArray.length){
if (changeAwayState){
changeAwayState = false;
writeText(awayArray[awayArrayPosition],"normal");
awayArrayPosition ++;
temp = pickRandomSpot();
randomX = temp[0];
randomY = temp[1];
}
else{
changeAwayState = true;
}
awayTimer=setTimeout("awayFn()",10000);
}
else{
abandoned = true;
whyGoneArrayPosition = 0;
whyGoneFn();
}
}
This is a deprecation error in Firefox 9. globalstorage was a way to store data in Firefox, but HTML5 introduced localstorage, which is now the preferred way (using window.localStorage).
https://developer.mozilla.org/en/DOM/Storage has more information.
I got the same error message and found a solution and perhaps the underlying cause of conflict, I was using the jQuery validate function in the jzaefferer.github.com/jquery-validation/jquery.validate.js library along with jQuery 1.7.1
The problem:
I used $(document).ready with two different contexts. One with the noConflict wrapper and one without. By keeping both the same, the error message went away. Hooray!
The wrapper:
jQuery.noConflict();
jQuery(function($) {
$(function() {
$(document).ready(function() { ...}
});
});
See also this post on my blog.
Probably not related to the issue above but I will put it here for the search engines.
I got the same error message while doing some simple jQuery:
Use of globalStorage is deprecated. Please use localStorage instead.
[Break On This Error]
$(document).ready(function() {
It was however due to forgetting to actually include the link href to the jQuery.js file...!

Intermittent JavaScript Issue

I'm running some JavaScript via eval (I know, shoot me), that basically enumerates all of the properties on the document object. My issue is that while it works in firebug, it throws a not implemented exception in Firefox, when run from a script.
Link to JavaScript script, the exception thrown, and the firebug command working.
Any suggestions as to what's going on here?
For the record, this is done on Firefox 3.6.10 on Ubuntu 10.04 64-bit, and chrome does not have this issue.
The error is here:
console.log(result);
remove that line and all should be fine.
The console object is a Firebug thing (refers to the Firebug console). Safari/Chrome just happen to also implement a console object (refers to Webkit js console). Firefox, indeed other browsers don't have a console object. So it throws an error.
BTW: As usual, the evals are completely unnecessary. This is exactly equivalent code:
for (key in document) {
result[i] = typeof document[key];
result[i+1]="document."+key;
i+=2;
}
If you insist on calling it request then use it as a reference:
var request = window.document;
for (key in request) {
result[i] = typeof request[key];
result[i+1]=request+"."+key;
i+=2;
}
If you insist on passing object names by string, then for sanity's sake use eval in a less confusing way:
var string = "window.document";
eval("var request ="+string);
for (key in request) {
result[i] = typeof request[key];
result[i+1]=request+"."+key;
i+=2;
}
Though I wouldn't do even that (sometimes it is necessary, but only very rarely).

Javascript replace a function with a new one containing dynamic contents

My Javascript knowledge is less experienced, so I might use wrong descriptions in the following.
I have an object in a static .js file:
var Info = {
methodA: function() {
// Call methodB.
this.methodB('test');
},
methodB: function(value) {
// Do stuff
}
}
Now, in an .aspx file, I create a function methodC(value) with varying contents (depending on some data), which I want to insert instead of the above definition of methodB(value):
...
var methodC = function(value) {
// Do different stuff
}
...
My idea has so far been to replace methodB with methodC in the following fashion:
...
Info.methodB = methodC;
...
Using IE's buildin developer tool, I get the following error when calling this.methodB('test'); from Info.methodA():
Object doesn’t support this property
or method
Removing the 'this' from this.methodB('test') results in the error:
Object expected
I don't get any errors using FireBug - probably because I use various frameworks, which might catch the error.
How should I do this or should I use a completely different approach?
Regards, Casper
It should work, you are doing it the right way. The problem lays elsewhere.
update:
This should still work as long as you call methodA on an object, eg Info.methodA().
Maybe you are not understanding the error messages ?
"Object doesn’t support this property or method" means that in the expression "this.methodB()", this doesn't have a property named "methodB". So it means that this is not Info when the code of methodA is executed.
"Object expected" means that the variable methodB is unknown in the current execution context. Of course it is, since methodB is never a variable, only a property of Info.
To debug your problem, you need to know what is this when a code is executed, and why it's not what you think it should be. When you call Info.methodA(), this is set to be Info when methodA begins its execution.

Log to Firefox Error Console from JavaScript

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,

Categories