I have a page which includes a js-file. It's a jquery Plugin, but I think thats not important. The plugin break with a manually thrown error at one point.
(function($) {
$.pkp.classes.Handler = function($element, options) {
/* ... */
if (this.data('handler') !== undefined) {
throw new Error('blub');
}
If I remove the line it works perfektly, so I think the check is not necessary. Unfortunatley I can not change the js-file (it would get overwritten every update), but I could savely include another one.
I tried to catch the error and let the script continue untouched as if the error throwing line where deleted.
$(window).error(function(e){
var t = 'Handler.js';
var l = t.length;
var file = e.originalEvent.filename.substr(e.originalEvent.filename.length - l, l);
if ((e.originalEvent.lineno == 38) && (file == t)) {
e.preventDefault();
return true;
}
})
I tried something similar with window.onerror. The result is, that in both cases the error doesn't appear, but the script does not continue as it would, if the line was deleted.
I know it would be better to find the source of the misbehaviour but its a very complicates bunch of scripts, and everything works still perfectly after I put a newer jQuery and a migration script there - only this single line makes problems, so I thought maybe it's more efficient just to eliminate the error without understanding it completely...
Any suggestions?
After i include the bootstrap.js
<script type="text/javascript" src="/js/bootstrap/js/bootstrap.js"></script>
I get followning error in the console:
Uncaught TypeError: Cannot read property 'documentElement' of null
The boots collapse works just fine but the console get spammed this error.
I have included jquery before bootstrap.
Anyone else had this problem before?
Edit:
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
this is a snipet from the bootstrap.js script.
It seems the error comes always in the tooltip function in the var inDom line at the documentElement part
You most likely have another tooltip library still in use (like JQueryUI/Tooltip) OR you're trying to attach a tooltip directly to the document element. Please look into your code for something like:
$(document).tooltip
or something like that, and remove it in order to make things work again. Be sure to review every other .tooltip() call you might already have, since they'll most likely not work anymore: you'll need to manually port them to Bootstrap in order to make them work again.
If you want to keep both Bootstrap/Tooltip and JQueryUI/Tooltip (assuming that's your scenario), you can use $.widget.bridge to manually change the JQueryUI tooltip plugin name:
// Change JQueryUI/tooltip plugin name to 'uitooltip' to fix name collision with Bootstrap/tooltip
$.widget.bridge('uitooltip', $.ui.tooltip);
You need to to this AFTER importing the JQueryUI js file and BEFORE importing the Bootstrap js file: while you're at it I also suggest you to do the same with button/uibutton to solve the exact same problem. The result code will look like that:
<script type="text/javascript" src="path/to/jqueryui.js" />
<script type="text/javascript">
// Change JQueryUI plugin names to fix name collision with Bootstrap:
$.widget.bridge('uitooltip', $.ui.tooltip);
$.widget.bridge('uibutton', $.ui.button);
</script>
<script type="text/javascript" src="path/to/bootstrap.js" />
Then you can just re-route your $(document).tooltip call to $(document).uitooltip to make everything work.
Alternatively, if you don't find the offending js code and/or you don't want to use $.widget.brige, you can always manually patch bootstrap.js to avoid this kind of error. This can be done by replacing the following line (#1384 in bs 3.3.1):
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
with this line:
var inDom = $.contains((this.$element[0].ownerDocument || this.$element[0]).documentElement, this.$element[0])
Keep in mind, tho, that you'll still have a broken .tooltip() call in your code somewhere.
See also:
http://www.ryadel.com/2015/01/03/using-jquery-ui-bootstrap-togheter-web-page/ (an article I wrote on my blog to better explain the issue)
https://github.com/twbs/bootstrap/issues/14483
http://jqueryui.com/tooltip/
Check whether the element is null before initialising it
i.e.
if($('[data-toggle="tooltip"]') != null)
{
$('[data-toggle="tooltip"]').tooltip();
}
I have created an ASP.Net application. I am using a javascript which is written in a separate file. I am using Var myvariableName ={} in javascript file.
I have included this file in MasterPage and accessing myvariableName in my aspx page.
This is working fine in Google Chrome, however, in IE 8 an unhandled exception is thrown as
myvariableName is undefined.
the error shows as;
0x800a1391 - Microsoft JScript runtime error: 'Common' is undefined
where Common is my javascript variable.
Please assist me in resolving this issue.
You're probably accessing the variable before your external script is executed.
Be sure to access your variable as soon as the document is fully loaded (i.e. $(document).ready(function(){...}); if you use jQuery) or try to find out the real execution order with some alert (that shouldn't be browser-depentent, by the way!).
If your code is already in a document.load or $(document).ready(function) you can always
handle the variable before acessing it via
if (typeof myvariableName !== "undefined") {
// do stuff
}
Some times in IE shit happens and window.load gets screwed specially when async calls are in place.
You are probably getting this error due to a missing semicolon. Change the code to this:
var myvariableName = {};
In your asp page, where you access your custom variable, wrap your code with:
var myvariableName = {};
window.onload = function(){
// your code here where you're accessing the variable
};
I have a graphics page which shows SVG graphics. I am using Raphael graphics framework. The page displays properly in Firefox, Also if the F12 developer tools is set 'on' in IE9 it works fine.
The map show partial data (its a node link diagram and it shows only one child node out of 12 nodes) in IE9 if the F12 developer mode is set off and application is started with browser cache cleared (simulating a general user).
Update: I kept the Debugger on and Shows me the error "Console is undefined". So I think its not a graphics rendering issue, and also I am not using the console explicitly, maybe the mindmap js is using it internally, but how to again get rid of this issue?
Update:
I found the issue and commented out the console.log entries from the js files.
Thanks.
Probably your code or the code you are calling is using console.log or something like it.
You could add this code in the global scope to create a dummy wrapper for IE (or any browser that doesn't support it). Just put the following code somewhere before you call any other libraries:
if(!(window.console && console.log)) {
console = {
log: function(){},
debug: function(){},
info: function(){},
warn: function(){},
error: function(){}
};
}
The problem is that your js code calls sometime a console method, for example 'console.log', but your browser does not have console (or has it closed);
To fix this, add this (once) before including any of your scripts:
//Ensures there will be no 'console is undefined' errors
window.console = window.console || (function(){
var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function(){};
return c;
})();
This will create a 'pseudo' console only if it doesn't exist, so that 'console is undefined' error will go away.
Hope this helps.
Cheers
Do you have a console.log() or console.error() call in your code?
I have a bunch of console.log() calls in my JavaScript.
Should I comment them out before I deploy to production?
I'd like to just leave them there, so I don't have to go to the trouble of re-adding the comments later on if I need to do any more debugging. Is this a bad idea?
It will cause Javascript errors, terminating the execution of the block of Javascript containing the error.
You could, however, define a dummy function that's a no-op when Firebug is not active:
if(typeof console === "undefined") {
console = { log: function() { } };
}
If you use any methods other than log, you would need to stub out those as well.
As others have already pointed it, leaving it in will cause errors in some browsers, but those errors can be worked around by putting in some stubs.
However, I would not only comment them out, but outright remove those lines. It just seems sloppy to do otherwise. Perhaps I'm being pedantic, but I don't think that "production" code should include "debug" code at all, even in commented form. If you leave comments in at all, those comments should describe what the code is doing, or the reasoning behind it--not blocks of disabled code. (Although, most comments should be removed automatically by your minification process. You are minimizing, right?)
Also, in several years of working with JavaScript, I can't recall ever coming back to a function and saying "Gee, I wish I'd left those console.logs in place here!" In general, when I am "done" with working on a function, and later have to come back to it, I'm coming back to fix some other problem. Whatever that new problem is, if the console.logs from a previous round of work could have been helpful, then I'd have spotted the problem the first time. In other words, if I come back to something, I'm not likely to need exactly the same debug information as I needed on previous occasions.
Just my two cents... Good luck!
Update after 13 years
I've changed my mind, and now agree with the comments that have accumulated on this answer over the years.
Some log messages provide long-term value to an application, even a client-side JavaScript application, and should be left in.
Other log messages are low-value noise and should be removed, or else they will drown out the high-value messages.
If you have a deployment script, you can use it to strip out the calls to console.log (and minify the file).
While you're at it, you can throw your JS through JSLint and log the violations for inspection (or prevent the deployment).
This is a great example of why you want to automate your deployment. If your process allows you to publish a js file with console.logs in it, at some point you will do it.
To my knowledge there is no shorter method of stubbing out console.log than the following 45 characters:
window.console||(console={log:function(){}});
That's the first of 3 different versions depending on which console methods you want to stub out all of them are tiny and all have been tested in IE6+ and modern browsers.
The other two versions cover varying other console methods. One covers the four basics and the other covers all known console methods for firebug and webkit. Again, in the tiniest file sizes possible.
That project is on github: https://github.com/andyet/ConsoleDummy.js
If you can think of any way to minimize the code further, contributions are welcomed.
-- EDIT -- May 16, 2012
I've since improved on this code. It's still tiny but adds the ability to turn the console output on and off: https://github.com/HenrikJoreteg/andlog
It was featured on The Changelog Show
You should at least create a dummy console.log if the object doesn't exist so your code won't throw errors on users' machines without firebug installed.
Another possibility would be to trigger logging only in 'debug mode', ie if a certain flag is set:
if(_debug) console.log('foo');
_debug && console.log('foo');
Hope it helps someone--I wrote a wrapper for it a while back, its slightly more flexible than the accepted solution.
Obviously, if you use other methods such as console.info etc, you can replicate the effect. when done with your staging environment, simply change the default C.debug to false for production and you won't have to change any other code / take lines out etc. Very easy to come back to and debug later on.
var C = {
// console wrapper
debug: true, // global debug on|off
quietDismiss: false, // may want to just drop, or alert instead
log: function() {
if (!C.debug) return false;
if (typeof console == 'object' && typeof console.log != "undefined") {
console.log.apply(this, arguments);
}
else {
if (!C.quietDismiss) {
var result = "";
for (var i = 0, l = arguments.length; i < l; i++)
result += arguments[i] + " ("+typeof arguments[i]+") ";
alert(result);
}
}
}
}; // end console wrapper.
// example data and object
var foo = "foo", bar = document.getElementById("divImage");
C.log(foo, bar);
// to surpress alerts on IE w/o a console:
C.quietDismiss = true;
C.log("this won't show if no console");
// to disable console completely everywhere:
C.debug = false;
C.log("this won't show ever");
this seems to work for me...
if (!window.console) {
window.console = {
log: function () {},
group: function () {},
error: function () {},
warn: function () {},
groupEnd: function () {}
};
}
Figured I would share a different perspective. Leaving this type of output visible to the outside world in a PCI application makes you non-compliant.
I agree that the console stub is a good approach. I've tried various console plugins, code snippets, including some fairly complex ones. They all had some problem in at least one browser, so I ended up going with something simple like below, which is an amalgamation of other snippets I've seen and some suggestions from the YUI team. It appears to function in IE8+, Firefox, Chrome and Safari (for Windows).
// To disable logging when posting a production release, just change this to false.
var debugMode = false;
// Support logging to console in all browsers even if the console is disabled.
var log = function (msg) {
debugMode && window.console && console.log ? console.log(msg) : null;
};
Note: It supports disabling logging to the console via a flag. Perhaps you could automate this via build scripts too. Alternatively, you could expose UI or some other mechanism to flip this flag at run time. You can get much more sophisticated of course, with logging levels, ajax submission of logs based on log threshold (e.g. all Error level statements are transmitted to the server for storage there etc.).
Many of these threads/questions around logging seem to think of log statements as debug code and not code instrumentation. Hence the desire to remove the log statements. Instrumentation is extremely useful when an application is in the wild and it's no longer as easy to attach a debugger or information is fed to you from a user or via support. You should never log anything sensitive, regardless of where it's been logged to so privacy/security should not be compromised. Once you think of the logging as instrumentation it now becomes production code and should be written to the same standard.
With applications using ever more complex javascript I think instrumentation is critical.
As other have mentions it will thrown an error in most browsers. In Firefox 4 it won't throw an error, the message is logged in the web developer console (new in Firefox 4).
One workaround to such mistakes that I really liked was de&&bug:
var de = true;
var bug = function() { console.log.apply(this, arguments); }
// within code
de&&bug(someObject);
A nice one-liner:
(!console) ? console.log=function(){} : console.log('Logging is supported.');
Yes, it's bad idea to let them running always in production.
What you can do is you can use console.debug which will console ONLY when the debugger is opened.
https://developer.mozilla.org/en-US/docs/Web/API/console/debug