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).
Related
if (open_date) {
open_date = get_date_from_string(open_date);
window.console && console.log(open_date);
window.console && console.log(cancel_until);
What is window.console && console.log ? Does it have to be in the code? Through this script does not work on IE (all version) --> IE runs javascript only after pressing F12
The rightside-expression will only get evaluated if the leftside-expression is truthy. Thats how the logical AND operator works.
Its basically short for
if( window.console ) {
console.log( open_date );
}
As you might guess correctly, it's a common pattern for this case, because the console object might not be available on every browser (especially mobiles).
1.) What is window.console && console.log ?
console.log refers to the console object used for debugging. for firefox i use firebug for example.
but if the console is not available the script will crash. so window.console checks if the console object is there and if so it uses its log function to print out some debug information.
2.) Does it have to be in the code?
no, its only for debugging purpose
window.console && console.log(open_date);
The above code is just short for an if conditional statement. It doesn't have to be there. it is for debugging purposes. For most browsers, you can hit F-12 to open the browser debug console. Chrome has a debug console built in. Firefox has an extension called FireBug that you can use. Below is the equivalent statement without the '&&'.
if (window.console) console.log(open_date);
I prefer to add the following code at the beginning of my javascript code so that I do not have to have these "if" statements all over the place. It really saves space and removes potential errors.
if (typeof console == "undefined") { window.console = {log: function() {}}; }
Jon Dvorak's comment above contains an elegant alternative way of doing this:
console = window.console || {log:function(){}}
Console.log is a logger for browser which logs the messages on browser console.
EDIT:
Console.log is not supported for lower versions of Internet Explorer
This condition is used to prevent errors on IE ... because, unfortunately, in IE (version 8) we cannot use console.log("") .... however testers still view the logs on Chrome ...
It fails after doing this:
<script type="text/javascript" src="/js/dojo-release-1.7.2-src/dojo/dojo.js"></script>
throwing an error on the statement (in this version, 1.7.2, it is line 260)
return new XMLHttpRequest();
being: "TypeError: Object doesn't support this method or property"
The silly thing is that this line is execute a lot of times (maybe even more than 100) without any problem, and it doesn't seem to be dependent on any variables. Unfortunately, at some point it fails. I swapped the line with:
try{
foo = new window.XMLHttpRequest();
return foo;
} catch(e) {
console.log("OUCH, ERROR.");
console.log(typeof window.XMLHttpRequest);
console.log(e);
}
which outputs:
OUCH ERROR.
object
TypeError: Object doesn't support this method or property
I am quite lost, as window.XMLHttpRequest seems to be an object, why can't I 'new' it? Any suggestion on how to debug this would be welcome.
What I find absolutely confusing is that this error only occurs when I go to this page using a link. when I refresh the page using F5, everything works, no errors, nothing.
Moreover, it runs flawless in internet explorer 9, firefox and chrome.
Clear cache completely in-browser
remove any components you have (activex) which are not native
if still issues
run xml-validation on your HTML
make sure the DOCTYPE is correct
check for selfclosing / non-closed tags
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");
}
Is there a console logger for IE? I'm trying to log a bunch of tests/assertions to the console but I can't do this in IE.
You can access IE8 script console by launching the "Developer Tools" (F12). Click the "Script" tab, then click "Console" on the right.
From within your JavaScript code, you can do any of the following:
<script type="text/javascript">
console.log('some msg');
console.info('information');
console.warn('some warning');
console.error('some error');
console.assert(false, 'YOU FAIL');
</script>
Also, you can clear the Console by calling console.clear().
NOTE: It appears you must launch the Developer Tools first then refresh your page for this to work.
Since version 8, Internet Explorer has its own console, like other browsers. However, if the console is not enabled, the console object does not exist and a call to console.log will throw an error.
Another option is to use log4javascript (full disclosure: written by me), which has its own logging console that works in all mainstream browsers, including IE >= 5, plus a wrapper for the browser's own console that avoids the issue of an undefined console.
Extremely important if using console.log() in production:
if you end up releasing console.log() commands to production you need to put in some kind of fix for IE - because console is only defined when in F12 debugging mode.
if (typeof console == "undefined") {
this.console = { log: function (msg) { alert(msg); } };
}
[obviously remove the alert(msg); statement once you've verified it works]
See also 'console' is undefined error for Internet Explorer for other solutions and more details
There is Firebug Lite which gives a lot of Firebug functionality in IE.
Simple IE7 and below shim that preserves Line Numbering for other browsers:
/* console shim*/
(function () {
var f = function () {};
if (!window.console) {
window.console = {
log:f, info:f, warn:f, debug:f, error:f
};
}
}());
In his book, "Secrets of Javascript Ninja", John Resig (creator of jQuery) has a really simple code which will handle cross-browser console.log issues. He explains that he would like to have a log message which works with all browsers and here is how he coded it:
function log() {
try {
console.log.apply(console, arguments);
} catch(e) {
try {
opera.postError.apply(opera, arguments);
}
catch(e) {
alert(Array.prototype.join.call( arguments, " "));
}
}
For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:
If console OR console.log undefined: Create dummy functions for
console functions (trace, debug, log, ...)
window.console = {
debug : function() {}, ...};
Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !
window.console = {
debug : window.console.log, ...};
Not sure about the assert support in various IE versions, but any suggestions are welcome.
You can use cross-browser wrapper: https://github.com/MichaelZelensky/log.js
For older version of IE (before IE8), it is not straight forward to see the console log in IE Developer Toolbar, after spending hours research and trying many different solutions, finally, the following toolbar is great tool for me:
http://www.my-debugbar.com/wiki/CompanionJS/Installing
The main advantage of this is providing a console for IE6 or IE7, so you can see what are the error (in the console log)
Note:
It is free
screen shot of the toolbar
I've been always doing something like this:
var log = (function () {
try {
return console.log;
}
catch (e) {
return function () {};
}
}());
and from that point just always use log(...), don't be too fancy using console.[warn|error|and so on], just keep it simple. I usually prefer simple solution then fancy external libraries, it usually pays off.
simple way to avoid problems with IE (with non existing console.log)
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,