Search code examples
javascriptdom-eventssettimeout

URL Change Event - JavaScript


I have a setTimeout that records the URL in a variable called newURL.

function checkURL() {
    var newURL = window.location;
} setInterval(checkURL, 1000);

What I would like to happen, is that a certain function must be executed, when the URL changes. Could someone help me here please?


Solution

  • Not sure why the page wouldn't reload before you could catch the change in the url. You can also take a look a window.onunload

    var checkURL = (function () {
        var oldURL = location.href;
        return function (fn) {
            var newURL = location.href;
            if (fn && oldURL !== newURL) {
                fn(oldURL, newURL);
            }
            oldURL = newURL;
        };
    }());