How can I use console logging in Internet Explorer? - javascript

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)

Related

What is window.console && console.log?

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 ...

jQuery BeautyOfCode Plugin remove alerts?

Is possible to remove alert() from the plugin when brushes are not founded?
Per my comment above, diverting alerts to console:
if (typeof(console) !== "undefined") {
window.alert = function(content) {
try {
window.console.log(content); /* send alerts to console.log if available. */
} catch(e) {}
}
}
Works great for "old-school" debugging, too. You can safely use "alert" instead of "console.log" and then when you test your application in a browser that doesn't have console you can still see your debugging output.
Note: in such browsers, alert will still appear. I presume this is a good thing, because the user will need to be told that something has failed. If this is NOT a good thing, because you want to avoid the warnings altogether, the above code will not necessarily help.

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).

Global JavaScript exception handler (in Chrome)

How do I overwrite the global Exception handler in JavaScript so that it becomes the top level handler for all uncaught exceptions?
window.onerror didn’t work. The code is:
<HTML>
<HEAD>
<script language='javascript'>
window.onerror = function (em, url, ln) {
alert(em + ", " + url + ", " + ln);
return false;
}
function fGo() {
try
{
var a = b; // Error here: b not defined
}
catch (e)
{
throw e;
}
}
</script>
</HEAD>
<BODY>
<button onclick='fGo()'>GO</button>
</BODY>
</HTML>
I'm testing on Chrome, by the way. The developer console registers the uncaught exception, but the alert() in window.onerror does not appear.
As of 2013, Chrome supports the window.onerror. (I have version 25, and comments imply earlier versions as well.)
I wrapped jQuery using currying to create a proxy that always does a try...catch in the jQuery functions.
I use it in www.js-analytics.com. However, the solution only holds for jQuery scripts.
Before 2013 Google Chrome didn't support window.onerror, and apparently it wasn't implemented in WebKit.
window.onerror = function(errorMsg, url, lineNumber) {
// Code to run when an error has occurred on the page
}
Chrome support for window.onerror
I believe support started in Chrome v10 (Chromium Issue 7771), but it looks as if "full" support with CORS support was resolved around Chrome 30+ (Chromium Issue 159566)
caniuse.com doesn't currently track this JavaScript feature (GitHub Issue 11999) ... to add support to this issue, log in to GitHub and "react" with a "Thumbs Up" on the original post (don't +1 in comments).
Current Google documentation for window.onerror
Chrome DevTools ~ Handle runtime exceptions using window.onerror
Perhaps you're looking for window.onerror. I am not sure whether this is available on all browsers.

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