用javascript获取相对URL

时间:2012-10-29 19:10:51

标签: javascript

有一种简单的方法来获取javascript的相对网址吗?我试图使用window.location.href,但它返回绝对路径。

我想做的是:我有两页; mobile.html和desktop.html。我想使用一个javascript文件来检测用户是在移动设备还是桌面上(我知道,这不是一个非常好的方法......),如下所示:

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";
    }
}

所以绝对路径的问题是,当测试mobile / desktop.html时,它们都进入无限循环页面刷新..

4 个答案:

答案 0 :(得分:5)

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';

答案 1 :(得分:1)

只测试它是否以HTML文件结尾。你可以使用正则表达式:

if(/desktop\.html$/.test(window.location.href)) {
     // code for desktop
} else if(/mobile\.html$/.test(window.location.href)) {
     // code for mobile
}

答案 2 :(得分:1)

另一个解决方案是找出location.href是否以mobile.html结尾,而不使用正则表达式:

if(window.location.href.indexOf("mobile.html") != (window.location.href.length - "mobile.html".length)) {
  ..
}

答案 3 :(得分:0)

URL.getRelativeURL

标准URL对象的防弹公共域扩展名为 getRelativeURL

这可以解决您的问题:

var loc = new URL(location.href); //get the current location
var dir = new URL(".", loc); //get the current directory
var rel = loc.getRelativeURL(dir); //relative link from dir to loc

if( rel !== "mobile.html" ){ ... }

Try it live. View on Gist.