使用 javascript 获取相对 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13128095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:52:53  来源:igfitidea点击:

get relative URL with javascript

javascript

提问by tobbe

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

有没有一种简单的方法可以使用 javascript 获取相对 url?我正在尝试使用,window.location.href但它返回绝对路径。

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:

我想要做的是:我有两页;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";
    }
}

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

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

回答by Trevor Dixon

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

回答by bfavaretto

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

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

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

回答by Zafer

Another solution to find out whether the location.href ends with mobile.html or not, without using regular expressions:

无需使用正则表达式即可找出 location.href 是否以 mobile.html 结尾的另一种解决方案:

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

回答by m93a

URL.getRelativeURL

URL.getRelativeURL

There's a bullet-proof public-domain extension for the standard URLobject called getRelativeURL.

标准URL对象有一个防弹公共域扩展名为getRelativeURL.

This would solve the problem for you:

这将为您解决问题:

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.

现场试一试。查看要点。