使用 window.location.href 和匹配的 URL 数组(一个用于桌面,一个用于移动)将桌面站点重定向到移动设备

Redirect desktop site to mobile using window.location.href and matching arrays of URLs (one for desktop one for mobile)

客户有两个网站:桌面和移动(不要问为什么桌面没有响应)。

桌面站点有许多页面实际上只是页面中的锚点。例如。 aboutus.html#team 现在必须在有人在小型移动设备上查看时重定向到 team.html。所有移动页面的名称都与桌面页面不同 (aboutus.html = about-us.html)。

与其在每个页面上放置代码以重定向该单独的页面(这没有办法重定向锚定的 URL),建议使用一个数组作为 desktopURLs,并使用一个相关的数组作为 mobileURLs。

所以(请注意,我在 http: 之后省略了 //,因此它们不会显示为链接,因为我没有足够的指向 post 链接的点数):

var desktopURL = ['http:domain.com/aboutus.html','http:domain.com/aboutus.html#/team','http:domain.com/contactus.html']
var mobileURL = ['http:m.domain.com/about-us.html','http:m.domain.com/team.html','http:m.domain.com/contact-us.html']

设置完成后,其中 desktopURL 索引 1 = mobileURL 索引 1。

我基本上需要在代码中说明这一点:

Get the window.location.href and look it up in desktopURL and return the index value.

Once you have the index value of desktopURL for the current window, update window.location.href with the object of the matching index number from the mobileURL array.

因此,当我是 phone 上的一个人并转到域时。com/aboutus。html 我会自动重定向到 m.domain。com/about-us.html

请注意,我无法更改移动网站上任何页面的名称(让它们与原始网站相匹配会更容易)。所以我需要找出一种代码方法来做到这一点,我已经进行了广泛的研究,但我不确定如何完成这个简单的任务。

这是JS:

var desktopURL = ['aboutus.html','aboutus.html#team','contactus.html']
var mobileURL = ['about-us.html','team.html','contact-us.html']

//Get the name of current page
var currPage=(window.location.href).split("/")[(window.location.href).split("/").length-1];
console.log(currPage);
var index=desktopURL.indexOf(currPage);
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location.href=mobileURL[index];

}

检查redirecttest[dot]webuda[dot]com

使用对象查找可以更好地处理您想要完成的任务。正如您所建议的那样,管理两个数组是非常脆弱的解决方案(那里不存在真正的关系,这将使 scale/maintain 变得困难)。

var MOBILE_ROOT = 'm.domain.com';
var LOOKUP = {
   '/aboutus.html':       '/about-us.html',
   '/aboutus.html#/team': '/team.html',
   '/contactus.html':     '/contact-us.html'
};

function redirect () {
    var path = window.location.pathname;
    var hash = window.location.hash;
    window.location.href = MOBILE_ROOT + LOOKUP[ path + hash ];
}

...

if ( //user agent lookup goes here ) {
    redirect();
}