简体   繁体   English

用javascript获取相对URL

[英]get relative URL with javascript

Is there an easy way to get the relative url with javascript? 有没有一种简单的方法来获取javascript的相对URL? Im trying to use window.location.href but it returns the absolute path. 我试图使用window.location.href但它返回绝对路径。

What im trying to do is this: I have two pages; 我想做的是:我有两页; mobile.html and desktop.html. mobile.html和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: 我想使用一个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时,它们都会进入无限循环页面刷新。

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. 只测试它是否以HTML文件结尾。 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
}

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

URL.getRelativeURL

There's a bullet-proof public-domain extension for the standard URL object called getRelativeURL . 有一个名为getRelativeURL的标准URL对象的防弹公共域扩展。

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. 在要点上查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM