0

I want to write a small function that takes a URL as a parameter, but before loading that URL, it checks if it is already on that page. If so, it returns false and nothing happens; otherwise, it loads the specified URL. I tried something like this:

function load(url) {
    if(window.location.href === url) {
        return false;
    } else {
        window.location.href = url;
    }
}

Unfortunately, if my current page is http://www.example.org/index.html, then, while calling load('http://www.example.org/index.html') does nothing, when I call load('index.html'), it reloads the page. How can I add the extra functionality to catch relative addresses as well as absolute ones?

EDIT: I want to make this dynamic, so that I can use this on any page, without knowing the base of its URL.

Bluefire
  • 13,519
  • 24
  • 74
  • 118
  • you can get a site's base url from its location by using one of the methods here: http://stackoverflow.com/questions/1420881/javascript-jquery-method-to-find-base-url-from-a-string -- then just combine that with my solution – user428517 May 16 '13 at 17:55

2 Answers2

0

This might work for you:

function load(url) {
    if(window.location.href === url || window.location.href === 'http://www.example.org/' + url) {
        return false;
    } else {
        window.location.href = url;
    }
}

But it's hard to know without knowing more about how the load function might be used.

user428517
  • 4,132
  • 1
  • 22
  • 39
0

Got it:

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

Then, the check becomes easy:

function load(url) {
    if(window.location.href.endsWith(url)) {
        return false;
    } else {
        window.location.href = url;
    }
}
Community
  • 1
  • 1
Bluefire
  • 13,519
  • 24
  • 74
  • 118