Find What caused a js function call using chrome developer tool - javascript

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.

Related

Why doesn't "console.log()" work on this website?

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.

Best Practice : Call a function from chrome dev console [duplicate]

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.

firefox / chrome console log of functions

Normally I use ff + firebug and I find extremely useful it's console feature: if you console.log(a_function); you don't see the (IMHO totally useless) function body, but a link to the js source file where the function is defined.
(On https://getfirebug.com/logging they describe it in the "Logging object hyperlinks" paragraph)
but but, is there a way to have the same behaviour on the firefox / chrome "native" console?
You could add console.trace() or even console.log() within the function definition to track it. Something like this:
function something(){
var x = 5 +3;
console.trace();
console.log("FUNCTION SOMETHING");
return x;
}
So, when it shows up in your Chrome console tools, you can see the originating file and line AND click on it to get to that file's source. Not as eloquent as FF Firebug, but it's a start.
I don't know if you have access to these functions and just want an easy way of going from the console to the source file OR truly don't know where the function originates. But this is what I would do. Check out the source for reference!
Source: https://developers.google.com/chrome-developer-tools/docs/console-api#consoletrace
In Chrome if you place your function in the console.dir function, you will get additional information about the function. You can then right click on the function and select "show function definition".
Example:
console.dir(my_function);
I'm not seeing anything in firefox.
Try to use
console.log("test");
It will work on both ff and chrome.
why not console.debug(yourfunc.toString()); ?

Calling a Javascript Function from Console

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.

Is there any way to fake the calling file in Firebug console?

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)

Categories

Resources