error in javascript or no clue - javascript

I got the following javascript code.
And Basically, it works on FF, and IE with developer Tools.
$(function(){
console.log("it is ok");
var mybutton="";
alert("ready1");
$('button[name="delorder"]').click(function(){
console.log($(this).val()+"hay i got a click");
mybutton=$(this).val();
alert("a click1");
$.ajax({
type:'POST',
url:'deleteorderitem.php',
data:mybutton,
success:function(result){
if((result.indexOf("t") < 3) && (result.indexOf("t") >= 0)){
$('#orderresult').html(result);
console.log("i am 3 ");
console.log("index of t is "+result.indexOf("t"));
}else{
console.log("i am 4");
console.log("index of t is "+result.indexOf("t"));
$('#divOrderButton').hide();
$('#orderresult').html("");
$('#divNoinfo').html("There is no record to display at the moment.");
$('#divNoinfo').show();
$('#divOrder').hide();
}
}
});
});
});
</script>
But , it does NOT WORK on IE (without developer tools).
so, any advice will be appreciated.
Thanks

It is mostly because of
console.log()
Windows IE8 and below has no console object when the Developer tools is not open.
Either comment out the lines that says console. Or create the console object beforehand.
Try this ... Not sure if this is the correct way around..
var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
if (alertFallback) {
console.log = function(msg) {
alert(msg);
};
} else {
console.log = function() {};
}
}
This will create the console object if it is not present.

If you're saying it doesn't work without developer tools open, (unless I'm mistaken) it is because you have all those console.log's and that must be what's blowing it up.
Try something like this at the very top of a master JS file to prevent that in IE.
if (typeof (console) === 'undefined' || !console) {
window.console = {};
window.console.log = function () { return; };
}

I use this function to write logs for cross browser console log :
/**
*Log into the console if defined
*/
function log(msg)
{
if (typeof console != "undefined") {
console.log(msg);
}
}

Related

Overwriting Console.log to Support Console.re.log to Debug iOS Chrome

I don't have any Apple devices and I'm trying to debug iOS Chrome. Sadly, browserstack doesn't have console support yet for iOS Chrome. I found this neat websocket console logger tool https://console.re/
It asks you to use special syntax to log to their app. You have to write console.re.log('message'). However, I'm trying to log everything to see where my app is breaking. I tried using the following code but I get problems with it going into infinite loops since console.re.log also calls console.log and I'm adding console.log to console.re.log... Here's the code:
<script>
console.log(window.location.href.slice(-5));
if(window.location.href.slice(-5) === 'debug') {
var consolere = {
channel:'music-blobs',
api:'//console.re/connector.js',
ready: function(c) {var d=document,s=d.createElement('script'),l;s.src=this.api;s.id='consolerescript';s.onreadystatechange=s.onload=function(){if(!l){c();}l=true;};d.getElementsByTagName('head')[0].appendChild(s);}};
var _log = console.log;
var _error = console.error;
var _warning = console.warn;
var logQueue = [];
var errorQueue = [];
var warnQueue = [];
var parseQueueRan = false;
consolere.ready(function() {
console.log = console.re.log;
console.warn = console.re.warn;
console.error = console.re.error;
});
window.console.log = function(...items) {
if(console.re) {
console.re.log(message);
} else {
logQueue.push(message);
_log.apply(console, arguments);
}
}
window.console.error = function(message) {
if(console.re) {
console.re.error(message);
} else {
errorQueue.push(message);
_warning.apply(console, arguments);
}
}
window.console.warn = function(message) {
if(console.re) {
console.re.warn(message);
} else {
warnQueue.push(message);
_error.apply(console, arguments);
}
}
}
</script>
Anybody know how I can get this working?
Its old, but for further Googlers:
My simple solution is:
console = console.re;
...and every log will be shown on console.re/

Debugging a background script in a Chrome extension

I'm trying to use some code from an open source library and I'm having some trouble logging to check where the code is failing.
In background.js:
chrome.extension.onRequest.addListener(function(request, sender, response) {
// This does not show in my console
console.log("request here");
switch(request.type) {
case 'enable?':
objectName.onTabSelect(sender.tab.id);
break;
case 'search':
// Also does not log here
console.log("Gets to first search item");
var e = objectName.search(request.text);
response(e);
break;
case 'open':
....
}
In content.js:
//This shows in my console
console.log("CHAR");
console.log(char);
document.body.innerText.match(/[\u3400-\u9FBF]/g).forEach(function (char) {
chrome.extension.sendRequest({
"type": "search",
"text": char
},
function (char_return) {
//This shows in my console, but is an empty obj and why I want to debug
console.log("char return");
console.log(char_return);
});
});
In main.js, a background script:
var objectName = {
...
search: function(text) {
// Does not log here. This is the area I REALLY want to log.
console.log("Char search gets here");
var entry = this.dict.wordSearch(text);
if (entry != null) {
for (var i = 0; i < entry.data.length; i++) {
var word = entry.data[i][1];
if (this.dict.hasKeyword(word) && (entry.matchLen == word.length)) {
// the final index should be the last one with the maximum length
entry.grammar = { keyword: word, index: i };
}
}
}
return entry;
}
}
How do I log in a background script? It looks like maybe I should be using the chrome.webRequest method? Could this be because some of the methods are deprecated? I intend on updating them to the new methods once I've got the application working, but to get it working I need to log and see where it is failing.
This is the first Chrome extension I've built so I'm not quite sure how this works.

How to detect if browser supports HTML5 Local Storage

The following code alerts ls exist in IE7:
if(window.localStorage) {
alert('ls exists');
} else {
alert('ls does not exist');
}
IE7 doesn't really support local storage but this still alerts it does. Perhaps this is because I am using IE9 in IE7 browser and document modes using the IE9 developer tool. Or maybe this is just the wrong way to test if LS is supported. What is the right way?
Also I don't want to use Modernizr since I am using only a few HTML5 features and loading a large script isn't worth it just to detect support for those few things.
You don't have to use modernizr, but you can use their method to detect if localStorage is supported
modernizr at github
test for localStorage
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 & Safari Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch(e) {
return false;
}
});
updated with current source code
if(typeof Storage !== "undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
This function works fine:
function supports_html5_storage(){
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
Source: www.diveintohtml5.info
Also I don't want to use Modernizr since I am using only a few HTML5
features and loading a large script isn't worth it just to detect
support for those few things.
To reduce Modernizr file size customize the file at http://modernizr.com/download/ to fit your needs. A localStorage-only version of Modernizr comes in at 1.55KB.
Try window.localStorage!==undefined:
if(window.localStorage!==undefined){
//Do something
}else{
alert('Your browser is outdated!');
}
You can also use typeof window.localStorage!=="undefined", but the statement above already does it
I didn't see it in the answers, but I think it's good to know that you can easily use vanilla JS or jQuery for such simple tests, and while Modernizr helps a lot, there are clean solutions without it.
If you use jQuery, you can do:
var _supportsLocalStorage = !!window.localStorage
&& $.isFunction(localStorage.getItem)
&& $.isFunction(localStorage.setItem)
&& $.isFunction(localStorage.removeItem);
Or, with pure Vanilla JavaScript:
var _supportsLocalStorage = !!window.localStorage
&& typeof localStorage.getItem === 'function'
&& typeof localStorage.setItem === 'function'
&& typeof localStorage.removeItem === 'function';
Then, you would simply do an IF to test the support:
if (_supportsLocalStorage) {
console.log('ls is supported');
alert('ls is supported');
}
So the whole idea is that whenever you need JavaScript features, you would first test the parent object and then the methods your code uses.
Try catch will do the job :
try{
localStorage.setItem("name",name.value);
localStorage.setItem("post",post.value);
}
catch(e){
alert(e.message);
}
Try:
if(typeof window.localStorage != 'undefined') {
}
if (window.localStorage){
alert('localStorage is supported');
window.localStorage.setItem("whatever", "string value");
}
Modifying Andrea's answer to add a getter makes it easier to use. With the below you simply say: if(ls)...
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
var ls = {
get: function () {
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
};
function script(){
if(ls){
alert('Yes');
} else {
alert('No');
}
}
<button onclick="script()">Local Storage Support?</button>
I know I'm a little late to the party, but I have a few useful functions I cooked up and threw into a file named 'manage_storage.js'. I hope they are as useful to you guys, as they have served me well.
Remember: The function you're looking for (that answers this question) is isLclStorageAllowed.
So without further ado here is my code:
/* Conditional Function checks a web browser for 'session storage' support. [BEGIN] */
if (typeof isSessStorageAllowed !== 'function')
{
function isSessStorageAllowed()
{
if (!!window.sessionStorage && typeof sessionStorage.getItem === 'function' && typeof sessionStorage.setItem === 'function' && typeof sessionStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ss_test_itm_key = 'ss_test_itm_' + String(cur_tm);
var ss_test_val = 'ss_test_val_' + String(cur_tm);
sessionStorage.setItem(ss_test_itm_key, String(ss_test_val));
if (sessionStorage.getItem(ss_test_itm_key) == String(ss_test_val))
{
return true;
}
else
{
return false;
};
sessionStorage.removeItem(ss_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'session storage' support. [END] */
/* Conditional Function checks a web browser for 'local storage' support. [BEGIN] */
if (typeof isLclStorageAllowed !== 'function')
{
function isLclStorageAllowed()
{
if (!!window.localStorage && typeof localStorage.getItem === 'function' && typeof localStorage.setItem === 'function' && typeof localStorage.removeItem === 'function')
{
try
{
var cur_dt = new Date();
var cur_tm = cur_dt.getTime();
var ls_test_itm_key = 'ls_test_itm_' + String(cur_tm);
var ls_test_val = 'ls_test_val_' + String(cur_tm);
localStorage.setItem(ls_test_itm_key, String(ls_test_val));
if (localStorage.getItem(ls_test_itm_key) == String(ls_test_val))
{
return true;
}
else
{
return false;
};
localStorage.removeItem(ls_test_itm_key);
}
catch (exception)
{
return false;
};
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'local storage' support. [END] */
/* Conditional Function checks a web browser for 'web storage' support. [BEGIN] */
/* Prerequisites: 'isSessStorageAllowed()', 'isLclStorageAllowed()' */
if (typeof isWebStorageAllowed !== 'function')
{
function isWebStorageAllowed()
{
if (isSessStorageAllowed() === true && isLclStorageAllowed() === true)
{
return true;
}
else
{
return false;
};
};
};
/* Conditional Function checks a web browser for 'web storage' support. [END] */

alias to chrome console.log

I would like to know why the follow code doesn't work in the Google Chrome:
// creates a xss console log
var cl = ( typeof( console ) != 'undefined' ) ? console.log : alert;
cl('teste');
output: Uncaught TypeError: Illegal invocation
thanks.
When you write cl();, you're calling log in the global context.
Chrome's console.log doesn't want to be called on the window object.
Instead, you can write
cl = function() { return console.log.apply(console, arguments); };
This will call log in the context of console.
https://groups.google.com/a/chromium.org/d/msg/chromium-bugs/gGVPJ1T-qA0/F8uSupbO2R8J
Apparently you can also defined log:
log = console.log.bind(console);
and then the line numbers also work
Unfortunately #SLaks answer isnt applied to IE because it uses window-object as context in console.log-method.
I would be suggest another way that doesnt depend on browser:
!window.console && (console = {});
console.debug = console.debug || $.noop;
console.info = console.info || $.noop;
console.warn = console.warn || $.noop;
console.log = console.log || $.noop;
var src = console, desc = {};
desc.prototype = src;
console = desc;
desc.log = function(message, exception) {
var msg = message + (exception ? ' (exception: ' + exception + ')' : ''), callstack = exception && exception.stack;
src.log(msg);
callstack && (src.log(callstack));
//logErrorUrl && $.post(logErrorUrl, { message: msg + (callstack || '') }); // Send clientside error message to serverside.
};

How do I print debug messages in the Google Chrome JavaScript Console?

How do I print debug messages in the Google Chrome JavaScript Console?
Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print() will send the parameter to the printer.
Executing following code from the browser address bar:
javascript: console.log(2);
successfully prints message to the "JavaScript Console" in Google Chrome.
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Just add a cool feature which a lot of developers miss:
console.log("this is %o, event is %o, host is %s", this, e, location.host);
This is the magical %o dump clickable and deep-browsable content of a JavaScript object. %s was shown just for a record.
Also this is cool too:
console.log("%s", new Error().stack);
Which gives a Java-like stack trace to the point of the new Error() invocation (including path to file and line number!).
Both %o and new Error().stack are available in Chrome and Firefox!
Also for stack traces in Firefox use:
console.trace();
As https://developer.mozilla.org/en-US/docs/Web/API/console says.
Happy hacking!
UPDATE: Some libraries are written by bad people which redefine the console object for their own purposes. To restore the original browser console after loading library, use:
delete console.log;
delete console.warn;
....
See Stack Overflow question Restoring console.log().
Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.
(Or create your own console.log() which just returns false.)
Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!
if (!window['console']) {
// Enable console
if (window['loadFirebugConsole']) {
window.loadFirebugConsole();
}
else {
// No console, use Firebug Lite
var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
if (F.getElementById(b))
return;
E = F[i+'NS']&&F.documentElement.namespaceURI;
E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
E[r]('id', b);
E[r]('src', I + g + T);
E[r](b, u);
(F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
E = new Image;
E[r]('src', I + L);
};
firebugLite(
document, 'createElement', 'setAttribute', 'getElementsByTagName',
'FirebugLite', '4', 'firebug-lite.js',
'releases/lite/latest/skin/xp/sprite.png',
'https://getfirebug.com/', '#startOpened');
}
}
else {
// Console is already available, no action needed.
}
In addition to Delan Azabani's answer, I like to share my console.js, and I use for the same purpose. I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug:
// Create a noop console object if the browser doesn't provide one...
if (!window.console){
window.console = {};
}
// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
if (!window.console.debug && typeof window.console.log !== 'undefined') {
window.console.debug = window.console.log;
}
}
// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
for (var i = 0; i < names.length; ++i){
if(!window.console[names[i]]){
window.console[names[i]] = function() {};
}
}
Or use this function:
function log(message){
if (typeof console == "object") {
console.log(message);
}
}
Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.
localConsole = {
info: function(caller, msg, args) {
if ( window.console && window.console.info ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.info.apply(console, params);
}
},
debug: function(caller, msg, args) {
if ( window.console && window.console.debug ) {
var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
if (args) {
params = params.concat(args);
}
console.debug.apply(console, params);
}
}
};
someClass = {
toString: function(){
return 'In scope of someClass';
},
someFunc: function() {
myObj = {
dr: 'zeus',
cat: 'hat'
};
localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
}
};
someClass.someFunc();
This gives output like so in Firebug:
In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}
Or Chrome:
In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object
Personally I use this, which is similar to tarek11011's:
// Use a less-common namespace than just 'log'
function myLog(msg)
{
// Attempt to send a message to the console
try
{
console.log(msg);
}
// Fail gracefully if it does not exist
catch(e){}
}
The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.
You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). Just press F12 and press the Console tab. You will see the result. Happy coding. :)
I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.
So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).
// Console extensions...
(function() {
var __localhost = (document.location.host === "localhost"),
__allow_examine = true;
if (!console) {
console = {};
}
console.__log = console.log;
console.log = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__log === "function") {
console.__log(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__info = console.info;
console.info = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__info === "function") {
console.__info(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__warn = console.warn;
console.warn = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__warn === "function") {
console.__warn(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__error = console.error;
console.error = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__error === "function") {
console.__error(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg);
}
}
};
console.__group = console.group;
console.group = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__group === "function") {
console.__group(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert("group:\r\n" + msg + "{");
}
}
};
console.__groupEnd = console.groupEnd;
console.groupEnd = function() {
if (__localhost) {
if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
console.__groupEnd(arguments);
} else {
var i, msg = "";
for (i = 0; i < arguments.length; ++i) {
msg += arguments[i] + "\r\n";
}
alert(msg + "\r\n}");
}
}
};
/// <summary>
/// Clever way to leave hundreds of debug output messages in the code,
/// but not see _everything_ when you only want to see _some_ of the
/// debugging messages.
/// </summary>
/// <remarks>
/// To enable __examine_() statements for sections/groups of code, type the
/// following in your browser's console:
/// top.__examine_ABC = true;
/// This will enable only the console.examine("ABC", ... ) statements
/// in the code.
/// </remarks>
console.examine = function() {
if (!__allow_examine) {
return;
}
if (arguments.length > 0) {
var obj = top["__examine_" + arguments[0]];
if (obj && obj === true) {
console.log(arguments.splice(0, 1));
}
}
};
})();
Example use:
console.log("hello");
Chrome/Firefox:
prints hello in the console window.
Internet Explorer:
displays an alert with 'hello'.
For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:
function doSomething(arg1) {
// ...
console.examine("someLabel", arg1);
// ...
}
And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):
top.__examine_someLabel = true;
Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.
Simple Internet Explorer 7 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
};
}
}());
console.debug("");
Using this method prints out the text in a bright blue color in the console.
Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....
You can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || console.log; // defaults to log
console.error = console.error || console.log; // defaults to log
console.info = console.info || console.log; // defaults to log
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Even though this question is old, and has good answers, I want to provide an update on other logging capabilities.
You can also print with groups:
console.group("Main");
console.group("Feature 1");
console.log("Enabled:", true);
console.log("Public:", true);
console.groupEnd();
console.group("Feature 2");
console.log("Enabled:", false);
console.warn("Error: Requires auth");
console.groupEnd();
Which prints:
This is supported by all major browsers according to this page:

Categories

Resources