Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get relative URL with javascript

Tags:

javascript

Is there an easy way to get the relative url with javascript? Im trying to use window.location.href but it returns the absolute path.

What im trying to do is this: I have two pages; mobile.html and desktop.html. I want to use ONE javascript-file to detect whether the user is on a mobile or desktop (I know, this is not a very good way to do it..) like this:

var is_mobile = //alot of text from http://detectmobilebrowsers.com/
                //that returns true/false, this works fine

if (is_mobile){

    if (window.location.href != "mobile.html"){
        window.location = "mobile.html";
    }
}

else {
    if (window.location.href != "desktop.html"){
        window.location ="desktop.html";
    }
}

So the problem with absolute path is that when testing either mobile/desktop.html they both go into infinite loop pagerefresh..

like image 812
tobbe Avatar asked Feb 19 '23 16:02

tobbe


2 Answers

var page = window.location.pathname.split('/').pop();

if (isMobile && page !== 'mobile.html')
    window.location = 'mobile.html';
else if (!isMobile && page !== 'desktop.html')
    window.location = 'desktop.html';
like image 94
Trevor Dixon Avatar answered Feb 21 '23 05:02

Trevor Dixon


Just test if it ends with either HTML file. You could use regular expressions:

if(/desktop\.html$/.test(window.location.href)) {
     // code for desktop
} else if(/mobile\.html$/.test(window.location.href)) {
     // code for mobile
}
like image 24
bfavaretto Avatar answered Feb 21 '23 06:02

bfavaretto