Retrieve console through javascript/jquery - javascript

I would like to send back the latest errors/log statements from the console as part of a support-request. I do I retrieve the console through javascript/jquery?

You can also override the console.log
(function(){
if(window.console && console.log){
var old = console.log;
console.log = function(){
doSomthingElse(arguments);
old.apply(this, arguments)
}
}
})();

You can use try... catch
See this example https://jsfiddle.net/j3tfLukr/
var a = {}
try {
var b = a.b.c
} catch(e) {
alert(e);
}

Related

how to mirror console.log in html page text box [duplicate]

Is it possible to extend the console object?
I tried something like:
Console.prototype.log = function(msg){
Console.prototype.log.call(msg);
alert(msg);
}
But this didn't work.
I want to add additional logging to the console object via a framework like log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.
Thanks in advance!
Try following:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
You Can Also add log Time in This Way :
added Momentjs or use New Date() instead of moment.
var oldConsole = console.log;
console.log = function(){
var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
Array.prototype.unshift.call(arguments, timestamp);
oldConsole.apply(this, arguments);
};
It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.
var _console={...console}
console.log = function(...args) {
var msg = {...args}[0];
//YOUR_CODE
_console.log(...args);
}
For ECMAScript 2015 and later
You can use the newer Proxy feature from the ECMAScript 2015 standard to "hijack" the global console.log.
Source-Code
'use strict';
class Mocker {
static mockConsoleLog() {
Mocker.oldGlobalConsole = window.console;
window.console = new Proxy(window.console, {
get(target, property) {
if (property === 'log') {
return function(...parameters) {
Mocker.consoleLogReturnValue = parameters.join(' ');
}
}
return target[property];
}
});
}
static unmockConsoleLog() {
window.console = Mocker.oldGlobalConsole;
}
}
Mocker.mockConsoleLog();
console.log('hello'); // nothing happens here
Mocker.unmockConsoleLog();
if (Mocker.consoleLogReturnValue === 'hello') {
console.log('Hello world!'); // Hello world!
alert(Mocker.consoleLogReturnValue);
// anything you want to do with the console log return value here...
}
Online Demo
Repl.it.
Node.js users...
... I do not forget you. You can take this source-code and replace window.console by gloabl.console to properly reference the console object (and of course, get rid of the alert call). In fact, I wrote this code initially and tested it on Node.js.
// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
if (!myclass || !myclass.verbose) // verbose switch
return;
var args = Array.prototype.slice.call(arguments); // toArray
args.unshift('Verbose:');
c.l.apply(this, args); // log
};
// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');
I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.
You can override the default behavior of the console.log function using the below approach, the below example demonstrates to log the line number using the overridden function.
let line = 0;
const log = console.log;
console.log = (...data) => log(`${++line} ===>`, ...data)
console.log(11, 1, 2)
console.log(11, 1, 'some')

Does the Chrome developer console have any aliases? [duplicate]

Is it possible to somehow access to console.log after it gets overwritten?
window.console = { log: function (msg) { alert(msg); }, /* etc... */ };
Would be it be possible to regain the original console.log functionality?
You can back up the console before overwriting it.
var oldConsole = window.console;
window.console = { log:function(msg){alert(msg)} //...};
Then you can use the oldConsole variable.
oldConsole.log('test');
If you can't back it up, you can create an iFrame, and then steal the console from there (this may not work in all browsers):
var i = document.createElement('iframe');
i.style.display = 'none';
document.body.appendChild(i);
window.console = i.contentWindow.console;
Demo: http://jsfiddle.net/jcG7E/2
Edit (2017-04-08): This advise is outdated, in Firefox 52 and Chrome 57 console is no longer defined on the window prototype and deleting it will really delete it.
At least with the console object defined by Firefox and Chrome, you can simply delete the overwritten property to restore the original one:
window.console = {};
delete window.console;
window.console.log("This works!");
This works as if the console property were defined on the prototype of the window object - except that it isn't, the browsers are doing some magic here.
It's not possible. Except if whoever has overwritten it has included some code to undo it.
var customLog = {
oriLog: '',
Log: function(){
// create string to display
var displaystring = '';
for (var i = 0, len = arguments.length; i < len; i++) {
displaystring += arguments[i];
if (i + 1 != len)
displaystring += ', ';
}
alert(displaystring);
customLog.oriLog(arguments);
}
}
window.onload = function(){
if (console != null) {
customLog.oriLog = console.log;
console.log = customLog.Log;
}
}

My callback function doesn't return "undefined" as I expect

I'm building a Chrome extension and I wrote this code.
I expect it prints 'Object {value: "set up"}' wnen I call options.getMode().
But, it prints 'undefined'.
var Options = function(){};
Options.prototype = {
getMode: function(){
chrome.storage.sync.get('value', function(e){
console.log(e); // it prints 'Object {value: "set up"}' in console.
return e;
})
}
}
var options = new Options();
console.log(options.getMode()); // it prints "undefined" in console.
The second argument for chrome.storage.sync.get() is a callback function.
I wonder if a callback function doesn't return the object(e).
I want it to prints out 'undefined' when I call options.getMode().
What's wrong with this code?
Please help me out!
I think I'm misunderstanding something very basic.
Thanks!!
Try this,
return chrome.storage.sync.get('value', function(e){
console.log(e); // it prints 'Object {value: "set up"}' in console.
return e;
});
Full code
var Options = function(){};
Options.prototype = {
getMode: function(){
return chrome.storage.sync.get('value', function(e){
console.log(e);
return e;
});
}
}
var options = new Options();
console.log(options.getMode());
Storage.get is asynchronous.
So your code should look like this:
var Options = function(){};
Options.prototype = {
getMode: function(callback){
chrome.storage.sync.get('value', function(e){
//this function is executed somewhere in the future
callback(e);
})
}
}
var options = new Options();
options.getMode(function(mode){
//do some stuff with mode here
console.log("Mode is", mode);
});

Adding some pre and post logic to a bunch of JavaScript methods

I have a JavaScript object
myObject = function () {
var that = {};
...
that.myMethod1 = myMethod1;
that.myMethod2 = myMethod2;
...
that.myMethodN = myMethodN;
return that;
}
I want to add the exact same pre and post logic to every method. For example a log for entering the method and for exiting the method.
I could with a prePostLogic function such as
function prePostLogic(f2) {
console.log('>> enter');
f2();
console.log('<< exist');
}
and then do:
myObject = {
...
that.myMethod1 = prePostLogic(myMethod1);
that.myMethod2 = prePostLogic(myMethod2);
...
that.myMethodN = prePostLogic(myMethodN);
return that;
}
But what I'd really like is to not have to wrap every method but to write something that would iterate over all methods and wrap them for me. This is so when someone adds a new method they don't have to wrap it.
Please help me?
Thanks
something that would iterate over all methods and wrap them for me
Exactly, just do that:
for (var prop in that)
that[prop] = makePrePostLogic(that[prop]);
function makePrePostLogic(fn) {
return function withLogic() {
console.log(">> enter "+fn.name);
var res = fn.apply(this, arguments);
console.log("<< exit "+fn.name);
return res;
};
}
function prePostLogic(f2) {
return (function(){
console.log('>> enter');
f2();
console.log('<< exit');
});
}
var func = function(){
console.log("Hello World");
}
var method = prePostLogic(func);
method();
In your case
for (var prop in myObject){
if(typeof myObject[prop] == "function"){
myObject[prop] = prePostLogic(myObject[prop]);
}
}

javascript: Error passing back object

I get an error passing back an object from function to calling function.
What am I doing wrong?
function stStartProcessing()
{
var returnValue = {};
returnValue = srGetNextRecord(); // returnValue is undefined
}
function srGetNextRecord()
{
var returnValue = {};
returnValue.addressToArray = "AAA";
returnValue.sequence = "111";
console.log(returnValue); // this works
return returnValue;
}
There must be a different problem in your code, since what you posted works fine.
The modified code below shows 111. See this DEMO
function stStartProcessing()
{
var returnValue = {};
returnValue = srGetNextRecord(); // returnValue is undefined -- no, it's not
console.log(returnValue.sequence); //shows 111
}
function srGetNextRecord()
{
var returnValue = {};
returnValue.addressToArray = "AAA";
returnValue.sequence = "111";
console.log(returnValue); // this works
return returnValue;
}
stStartProcessing();
On a separate note, when writing JavaScript, please get into the habit of putting your opening braces on the same line—always. For what you have above it won't make a difference, but if you ever do this:
function foo()
{
return
{
x: 1,
y: 2
};
}
horrible things will happen—a semicolon will be inserted after the word return, thereby killing your return value, and causing a script error.

Categories

Resources