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?
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?
Share Improve this question edited Jul 3, 2020 at 21:34 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 11, 2012 at 13:45 Jacques BlomJacques Blom 1,8226 gold badges25 silver badges44 bronze badges 4- 1 Whouldn't the url change be caused by page reloading? – WojtekT 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 pare 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. – Felix Kling Commented Jun 11, 2012 at 13:48
- @WojtekT: The URL can be changed by a number of ways. – Felix Kling Commented Jun 11, 2012 at 13:51
- Felix Kling is right. The page is using the History API. Sindri's answer helped. Thanks! – Jacques Blom Commented Jun 11, 2012 at 13:54
3 Answers
Reset to default 4Not 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;
};
}());
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.
Use a global variable to store old url. Than you can check if the url was changed and execute some function.