I have a lot of console.log in my script, and I don't want them slowing my script down when I don't have the console open.
So my question is, do they execute when the console is closed? Because if they do I would have to comment them out, and then uncomment them every time I need to see them.
Yes, console.log() in your code will execute without the console open on the web page.
In all the browsers I know of, they do execute even while the console is closed - for example, try running the following code with the console closed, then open the console after 5 seconds, and you'll see that the console has indeed been populated with the text:
setInterval(() => {
console.log('log');
}, 1000);
The performance impact of console.log is next to nothing, but if you wanted an easy way to toggle between having console.log calls print to the console, and do nothing, you can define a console variable on the top level of your userscript that has a log function which does nothing, thus shadowing window.console.log inside the scope of your userscript:
const console = { log: () => void 0 };
console.log('foo');
To print to the console normally again, just comment out the const console... line (or use a boolean variable doPrintToConsole or something).
This will not prevent native page scripts from console.logging. (If you wanted to prevent native page scripts from doing so, overwrite window.console.log instead);
Related
I can open the Chrome DevTools console for this URL: https://www.google.com/ and enter the following command to print "Hello world!" to the console:
console.log("Hello world!")
However, when I attempt to use the same command for this URL: https://svc.mt.gov/dor/property/prc my message isn't printed in the console. Why is that?
Is there any way to force the console to work for this MT website?
I've tried using python/selenium to open the page and execute_script() to issue the command, but that hasn't worked either.
If you do
console.dir(console.log)
and click on the [[FunctionLocation]], you'll see the following in the site's source code:
"Debug" != e && (window.console.log = function() {}
)
Seems like a cheap (but lazy?) way to suppress logging on production.
One way to fix it, kinda, would be to use one of the many other console commands. (console.dir, or console.error, if you want)
If you really want the original console.log to work again, the only way to do that would be to run code before the page code runs, so that you can save a reference to the function. For example, with a userscript:
// <metadata block...>
// #grant none
// ==/UserScript==
const origConsoleLog = console.log;
// set original window.console.log back to its original
// after the page loads
setTimeout(() => {
window.console.log = origConsoleLog;
}, 2000);
// there are more elegant but more complicated approaches too
CertainPerformance already explained how this is possible and what the reason for suppressing the log seems to be. I'm going to show here another method to get back console.log after the original has been lost.
document.body.appendChild(document.createElement('IFRAME')).onload = function () {
this.contentWindow.console.log('Hello, World!');
this.remove();
};
This basically uses an old method of restoring global objects from a temporary iframe.
In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName(); and hit return.
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
})
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
})
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox):
http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.
In my web page, I get a "alert" that I want to know what causes it to fire and appear in page. Is it possible to use chrome developer tools to find it ?
You can bind some function of yours to window.alert;
alert = function myCustomAlert(){ console.log("caller", myCustomAlert.caller); }
You can place this at developer tools console and inspect the caller.
You can do this with other techniques like :
alert = function myCustomAlert(){ console.log("caller", arguments.callee.caller.name); }
The only problem with this is that it has to run on a non-strict scope.
Yes go the page where you are getting this alert and open developer tool and go inside "Elements" tab and do a search of text "alert"
( CTRL+F in windows or CMD+F in Mac)
. you should find the line of code which is firing the alert actual code should be something like window.alert("message which you are seeing on screen");
or alternate way is right click on page and do
"view page source"
and search of same text "alert" you should get the line of code.
Try to assign new function to a window.alert property and print stack trace using console.trace():
window.alert = (function( window ) {
var oldAlert = window.alert;
return function alert( message ) {
console.trace();
oldAlert( message );
};
})( window );
Stack trace is better than caller name because it works in strict mode and it provides more information. But this code snippet will not work if alert is called by setTimeout, setInterval or as a event handler:
// In this case stack trace consists of single alert call.
setTimeout(alert, 0, "foo");
So if this solution does not help you, you probably need to replace other functions (setTimeout, setInterval, addEventListener) in similar manner as well. For more information you can look at Long stacktraces project.
In Chrome's JavaScript console, how do I call a function that belongs to a .js file included in the webpage I am viewing?
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName(); and hit return.
An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function
//this will fail
$(document).ready(function () {
myFunction(alert('doing something!'));
//other stuff
})
To succeed move the function outside the document ready function
//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {
//other stuff
})
Then in the console window, type the function name with the '()' to execute the function
myFunction()
Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name
function myFunction(alert('doing something!'))
Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox):
http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You can invoke it using
window.function_name()
or directly without window like
function_name()
Basically, there are two cases here:
Your function is in global scope. In that case, simply open a console and call it yourFunction()
Your function is scoped inside some other function(s) and is not accessed globally. In that case, you can open a Sources tab, locate your .js file, place a breakpoint anywhere at the bottom of the outer function (you might need to refresh a page after that if the code have already been run) and call yourFunction() in console. Also, while at breakpoint you may do something like window.yourFuncRef = yourFunction in console, to be able to access it later at any time.
I just discovered this issue. I was able to get around it by using indirection. In each module define a function, lets call it indirect:
function indirect(js) { return eval(js); }
With that function in each module, you can then execute any code in the context of it.
E.g. if you had this import in your module:
import { imported_fn } from "./import.js";
You could then get the results of calling imported_fn from the console by doing this:
indirect("imported_fn()");
Using eval was my first thought, but it doesn't work. My hypothesis is that calling eval from the console remains in the context of console, and we need to execute in the context of the module.
Note: Firebug being Firebug extension and/or Webkit developer tools.
With the faking of calling file I mean the link at the right side of the console output, pointing to the location where the output function (like console.log) is called.
This becomes a problem when you have unified handler for error messaging etc, thus all the console.log calls originate from the same file & linenumber.
Is there any way to fake this information? Or bake such link (pointing to line number) into the firebug console log (providing one has the stacktrace)? Just adding the filename and line number to the end of any log adds noise to the console output, making it messy.
Most modern browsers define a console.log function. How about instead of writing your own error handler, you go ahead and call console.log everywhere you have an error. Then, for the browsers that do not define console.log, you can define it yourself using whatever you want. For instance, if you wanted to alert the error in IE (or FF without firebug installed.. etc) you could use this code:
<html>
<head>
<title>Test</title>
</head>
<body>
<button onclick="throwError()">
Throw Error</button>
<script type="text/javascript">
function throwError() {
console.log("error here!");
}
if (!window.console) {
window.console = {
log: function(e) {
alert(e);
}
};
}
//Added in EDIT: in production add these lines below to overwrite browser's console.log function
window.console.log = function(e) {
alert("production alert: " + e); //or whatever custom error logging you want
};
</script>
</body>
</html>
You can add whatever you want to the console object. I've tested this in IE8 and Firefox, and I'm fairly confident you can make this idea work for whatever set of browsers you support.
EDIT: Looks like you can also overwrite the default console.log function in Firefox, Safari, and Chrome. Just remap the log member of the console object to a new function that does whatever you want while in production.
Taking a brief trawl on the firebug forums it seems to imply that it (sometimes?) looks at the exception to determine what the line number is.
So you may well be able to fake it that way by judicious massaging.
With Firebug there is an option to show the call stack alongside errors.
Click on the down arrow next to the console tab's name to see and activate it.
It causes a 'plus' icon to show to the left of the message, which reveals the stack.
This might get you closer the code that caused the error.
If you will also need to log errors with console.error() to make use of this.
(not sure how compatible this is with chrome though)