Babak Fakhriloo
Babak Fakhriloo

Reputation: 2126

Find What caused a js function call using chrome developer tool

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 ?

Upvotes: 0

Views: 115

Answers (3)

Lionia Vasilev
Lionia Vasilev

Reputation: 12748

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.

Upvotes: 0

MGA
MGA

Reputation: 531

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.

Upvotes: 2

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

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.

Upvotes: 2

Related Questions