printing stack trace of javascript console - javascript

I am trying to type a javascript code in an textarea and display the result of it in a div.
I went through a similar question:
showing-console-errors-and-alerts-in-a-div-inside-the-page
It works fine for any explicit console statements. But when there are any syntax errors in the code written in the text area, the error message is shown on only in the console and not captured in the code.
The code I am using is:
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('#result').append('<p>' + message + '</p>');
};
console.error = console.debug = console.info = console.log
This works if I type console.log("hello") in the textarea.
But when I type console.log("he deliberately, the error is shown only in the browser console. Is there a way I can capture such messages and display it?

Same way browser console does it.
Add try...catch to your code.

You can use window.onerror to solve the problem, try
window.onerror = function(e) {
console.log(e.stack);
}

Related

Read console.log() output form javascript

I am writing an overlay UI for one application using Greasemonkey, injecting JS to a page.
Now I have issue to hook on some ajax calls that runs on the webpage.
However, the page is generating console logs, informing that content is fully loaded. My question is:
In plain javascript, is there a possibility of reading console output generated by completely different script?
function blackBox(){
//this is generating come console output.
//this runs on code layer I have no access to.
}
function readConsole(){
//read console record by record
if(console.msg == "something I want"){
doSomething();
}
}
Thanks in advance :)
As others have stated, you can override the console.log() function with your own, and implement your own implementation:
var oldLog = unsafeWindow.console.log;
var messages = [];
unsafeWindow.console.log = function(msg) {
messages.push(msg);
oldLog.apply(null, arguments);
}
// Access the entire console.log history in messages
Redefine console.log and storage messages on a array:
var consoleStorage = [];
console.log = function(msg){
consoleStorage.push(msg);
console.warn(msg); // if you need to print the output
}
Now you can read all logs:
function readConsole(){
//read console record by record
consoleStorage.forEach(msg => {
doSomething(msg);
});
}
Even if it were possible, that would be bad practice. The console is for human eyes to see, when debugging. It usually takes several milliseconds to execute console.log, so executing it in production code is not a good idea.
I would say programming in booleans (like ifDidX and ifDidY) would be better. But if you really had to do this message-history thing, a better alternative would be to store messages in some other array. Here is an example:
var messagesLog = [];
//Since console.log takes several milliseconds to execute, you should tick this to false in production code.
const logToConsole = true;
function logMessage( message ){
//adds message to JS log.
messagesLog.push(message);
//performs console.log if not production code
if(logToConsole){
console.log(message);
}
}
logMessage("pizza");
logMessage("second to last message");
logMessage("last message");
//checks last message and this will be true
if( messagesLog[messagesLog.length - 1] == "last message" ){
logMessage("The last message in the log was 'last message'");
}
//checks last message and this will be false
if( messagesLog[messagesLog.length - 1] == "pizza" ){
logMessage("This will not occur because the last message was 'last message'");
}
//searches through log to find certain message
for(let i = 0; i < messagesLog.length; i++){
if(messagesLog[i] == "pizza"){
logMessage("one of the messages in the log was pizza");
}
}
Directly there's no way to access console outputs, but what you can do is that you can override console.log in a way where it checks for you condition first and then outputs the content, below is a sample code for that
console.stdlog = console.log.bind(console);
console.log = function(msg){
if(msg == "something I want"){
...
}
console.stdlog.apply(console, arguments);
}
Although you'll need to be very careful with this since if you add any console.log in that condition, it will create an infinite loop.

Javascript debug no console error

My script dont run till the end. And stops due to errors. But there is no console error output.
alert("yo");
var go = "";
go.push(null);
alert("yo2");
first alert works
Tested with Chrome and Firefox
No try catch blocks
Are there reasons for not showing up a console error, without knowing the whole code?
You should see the error: TypeError: Object has no method 'push'
Im getting it in chrome console.
The error message is saying that the push method cannot be run on the variable go.
This is because it is of the type String and thus does have the push method available.
The push method is used to add items into an Array like this:
go = []; // or you could use `go = Array()`;
go.push("A string");
go.push(null);
To output messages to the browser console, use console.log like this:
console.log("Some debug message");
console.log(go); // outputs the above array
I solved the problem by using try-catch:
try
{
var my_app = new My_App();
}
catch(e)
{
console.log("ERROR"+e);
}
Now i get the console output.

Show an alert or popup if a Javascript error occurs

Is it possible to get visuel notifyed if I get a Javascript error?
In developing I have Firebug or something else open so I spot it.
But in the case where I do a light demostration for someone else I can not have it open.
I still prefer to know about the error instead of it failing silently and I dont know about trailings errors where I can't distinct wish between real and trailing errors.
You can surround your code in a try-catch and call alert with the error message. For example, if your code is as follows:
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
you can surround it with the try-catch as follows:
try {
var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception
}
catch(err) {
alert(err.message);
}
err.message basically contains the error message, similar to the one you see in Firebug.
Edit: You may also define window.onerror. See this answer
I believe you can use try catch functionality to show the error.
Something like this:
try {var a = 20 / f;}
catch (err) {alert(err);}
http://jsfiddle.net/magwalls/h7kqr/
Hope this helps!

Is there any way to get the origin of an alert box?

I work with some very large and confusing JavaScript files that I did not write. Sometimes an alert will come up but I don't know where it's coming from.
You could search all files for the text contained in the alert but if that text is dynamic it won't work.
Is there a way to set a breakpoint in order to intercept an alert?
At the very top of your HTML:
window.alert = function() {
debugger;
}
debugger is a statement that invokes any debugging functionality available. With developer tools open, you'll automatically hit a breakpoint whenever alert is called. You can then inspect the call stack to see exactly what called the custom alert function.
It may or may not be helpful to you, but you can overwrite the alert function to do whatever you want with it. For example, instead of alert boxes, you could have it log the message to the console.
window.alert = function(msg) {
console.log(msg);
}
alert('test');
I agree with Brian Glaz, but in order to get more details (line number) you might try to throw an error when alerting something and outputting the error on the console. this way, the console will point you to the right line number where the alert function was called.
Put this snippet at the top of your document and give it a try :
var originalAlert = window.alert;
window.alert = function(){
try{
throw new Error('alert was called');
} catch(e){
console.warn(e);
}
return originalAlert.apply(window, arguments);
}
Open Chrome push F12 key and go to Sources.
Then choose a script file Ctrl+F and search for alert.
You can put breakpoint on any line you wish

JavaScript: How do I print a message to the error console?

How can I print a message to the error console, preferably including a variable?
For example, something like:
print('x=%d', x);
Install Firebug and then you can use console.log(...) and console.debug(...), etc. (see the documentation for more).
console.error(message); // Outputs an error message to the Web Console
console.log(message); // Outputs a message to the Web Console
console.warn(message); // Outputs a warning message to the Web Console
console.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small "i" in front of the message.
You also can add CSS:
console.log('%c My message here', "background: blue; color: white; padding-left:10px;");
More info can be found here: https://developer.mozilla.org/en-US/docs/Web/API/console
Exceptions are logged into the JavaScript console. You can use that if you want to keep Firebug disabled.
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0);
}
Usage:
log('Hello World');
log('another message');
One good way to do this that works cross-browser is outlined in Debugging JavaScript: Throw Away Your Alerts!.
Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)
As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):
var startTime = (new Date()).getTime();
function logError(msg)
{
var milliseconds = (new Date()).getTime() - startTime;
window.setTimeout(function () {
throw( new Error(milliseconds + ': ' + msg, "") );
});
}
logError('testing');
I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.
The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.
It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.
Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.
If you use Safari, you can write
console.log("your message here");
and it appears right on the console of the browser.
To actually answer the question:
console.error('An error occurred!');
console.error('An error occurred! ', 'My variable = ', myVar);
console.error('An error occurred! ' + 'My variable = ' + myVar);
Instead of error, you can also use info, log or warn.
If you are using Firebug and need to support IE, Safari or Opera as well, Firebug Lite adds console.log() support to these browsers.
The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).
A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging "on going processes" (like to track a certain variable...)
My suggestion is perhaps to add a textarea element somewhere in your document and to change (or append to) its value (which would change its text) for logging information whenever needed...
As always, Internet Explorer is the big elephant in rollerskates that stops you just simply using console.log().
jQuery's log can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:
function log()
{
if (arguments.length > 0)
{
// Join for graceful degregation
var args = (arguments.length > 1) ? Array.prototype.join.call(arguments, " ") : arguments[0];
// This is the standard; Firebug and newer WebKit browsers support this.
try {
console.log(args);
return true;
} catch(e) {
// Newer Opera browsers support posting erros to their consoles.
try {
opera.postError(args);
return true;
}
catch(e)
{
}
}
// Catch all; a good old alert box.
alert(args);
return false;
}
}
Visit https://developer.chrome.com/devtools/docs/console-api for a complete console api reference
console.error(object[Obj,....])\
In this case, object would be your error string
function foo() {
function bar() {
console.trace("Tracing is Done here");
}
bar();
}
foo();
console.log(console); //to print console object
console.clear('console.clear'); //to clear console
console.log('console.log'); //to print log message
console.info('console.info'); //to print log message
console.debug('console.debug'); //to debug message
console.warn('console.warn'); //to print Warning
console.error('console.error'); //to print Error
console.table(["car", "fruits", "color"]);//to print data in table structure
console.assert('console.assert'); //to print Error
console.dir({"name":"test"});//to print object
console.dirxml({"name":"test"});//to print object as xml formate
To Print Error:- console.error('x=%d', x);
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
console.log("your message here");
working for me.. i'm searching for this.. i used Firefox.
here is my Script.
$('document').ready(function() {
console.log('all images are loaded');
});
works in Firefox and Chrome.
The simplest way to do this is:
console.warn("Text to print on console");
To answer your question you can use ES6 features,
var var=10;
console.log(`var=${var}`);
This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:
just do:
alert("message");
With es6 syntax you can use:
console.log(`x = ${x}`);

Categories

Resources