使用JavaScript获取相对URL

4
有没有一种简单的方法来使用JavaScript获取相对URL?我正在尝试使用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.html 还是 desktop.html,它们都会进入无限循环刷新页面的状态。


这个问题有一个不错的解决方案在这里:https://dev59.com/MG025IYBdhLWcg3wAxF9 - Werner Kvalem Vesterås
4个回答

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

太棒了!这正是我在寻找的。但你能解释一下.split()和.pop()都是做什么的吗?我猜split是将字符串按'/'分割,但它返回一个数组还是什么呢?而在这里.pop()又是干什么的呢?谢谢! - tobbe
是的,split返回一个数组,而.pop()返回数组的最后一个元素。'/foo/bar/mobile.html'.split('/') 返回 ['foo', 'bar', 'mobile.html']['foo', 'bar', 'mobile.html'].pop() 返回字符串 'mobile.html'。(在Chrome开发工具或Firebug中尝试一下吧。) - Trevor Dixon

1

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

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

1

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

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

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" ){ ... }

现场试用。 在Gist上查看。


1
仅仅是一个提醒,你不应该以这种方式扩展内置对象,因为(a)它可能会导致与标准库(或尝试进行类似修改的其他库)的未来添加发生冲突!(b)它使得很难识别正在运行的代码,这对于人类和捆绑程序都是一种痛苦(在模块化的世界中,像这样导入东西纯粹是副作用,这是非常不可取的)。这应该作为一个独立的函数实现。 - Chris Morgan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接