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 ...
Related
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.
I've a weird bug where AngularJS doesn't appear to parse/compile the mustache and bind it to a variable on the first loading of the site (see screenshot). The problem goes away if I enter into development mode and refresh the page; hence it becomes hard to debug since I can't see the errors.
There is a live version of the site available at http://www.notable.ac
If it's the console issue...
Just add a stub in the root of your JS:
//make sure console.log exists in ie.
window.console = window.console || {};
window.console.log = window.console.log || function(){};
console is not available in IE with dev tools disabled,
you can just test:
if(console && console.log) {
console.log('ok');
}
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).
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,