Search code examples
javascripthtmlgeolocationgoogle-chrome-devtoolsfirefox-developer-tools

How can I debug which script is trying to use the Geolocation API?


On my site, I have a bunch of trackers loaded via Google Tag Manager, including Google Analytics and Chartbeat, along with a bunch of DoubleClick For Publishers (DFP) ads.

On mobile only, when someone visits my site they get the "example.com would like to use your location" notification, but I can't determine what is trying to access that information.

How can I debug which script is trying to use the Geolocation API, using Firefox or Chrome?


Solution

  • The Geolocation API has a function called getCurrentPosition, which is what is getting called.

    If you don't know where that call is happening because you have a large code base, or it's happening in a client library, it can be pretty difficult to find.

    One option would be to search the solution in the Sources panel. You can do this using the shortcut Cmd + Opt + F (Mac) or Ctrl + Shift + F (Windows), and search for "geolocation" or part of the API call. You should see a list of results in the panel.

    Another useful solution is a method I like to call Debugging JavaScript by Redefining Functions. The idea is to store a copy of the original function, override it and inject your debugging logic, and then call the original function from the current context.

    Using this, we can inject a debugger statement into the getCurrentPosition function, so that whenever it gets called, the debugger will break and you will have a call stack in DevTools.

    var oldGetCurrentPosition = navigator.geolocation.getCurrentPosition;
    
    navigator.geolocation.getCurrentPosition = function() {
        debugger;
        return oldGetCurrentPosition.apply(this, arguments);
    }
    

    I would run this in the Console, using a Snippet preferably, so as to avoid this debugging code appearing in production. The good thing is the logic doesn't break the original code if it did.