0

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?

4
  • 1
    Whouldn't the url change be caused by page reloading? Commented Jun 11, 2012 at 13:48
  • Assuming the only fragment identifier is changed or the URL is changed through the history API, all you have to do is compare the current value against the previous one. I don't see the difficulty here. But if changing the URL causes a reload of the page, it does not matter what you do, since your script will terminate. Commented Jun 11, 2012 at 13:48
  • @WojtekT: The URL can be changed by a number of ways. Commented Jun 11, 2012 at 13:51
  • Felix Kling is right. The page is using the History API. Sindri's answer helped. Thanks! Commented Jun 11, 2012 at 13:54

3 Answers 3

4

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;
    };
}());
Sign up to request clarification or add additional context in comments.

Comments

1

From what i understand, when the url changes will be a new execution of the JS scripts in that page. The " window.location" will return the current URL, but JavaScript not record /register data in script, or variablle from a page to another.

Comments

0

Use a global variable to store old url. Than you can check if the url was changed and execute some function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.