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..
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';
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With