JS根据用户代理重定向?

问题描述

如果这个问题很明显可以解决,我很抱歉,但我还不知道 JavaScript,但感觉这是实现我的客户对其网站所需的唯一方法

我想在用户访问主页后将使用特定浏览器的用户重定向到特定的简化页面,并在他们每次点击主页按钮时保持此重定向工作。基本上我想要的是基于用户代理的 301 重定向。我已经尝试了很多次,但我得到的只是无限重定向循环或根本没有结果。

function get_ya_browser(){
var ua = navigator.userAgent;    
if (ua.search(/Yabrowser/) > 0) document.location.href='redirect-link.html';
return '';
}

如何更改此代码才能工作?非常感谢您的帮助。

解决方法

尝试 - document.location.replace ='redirect-link.html'; 而不是 document.location.href ='redirect-link.html';

.location.replace() 模拟 HTTP 重定向 .location.href() 模拟鼠标点击

,

如果代码是 redirect-link.html && ua.search(/YaBrowser/) !== -1 的一部分,你会得到一个无限循环。

以下代码解决了这个问题:

function get_ya_browser(){
   var ua = navigator.userAgent;    
   if (ua.search(/YaBrowser/) !== -1 && !location.href.includes('elbrus-m-zakaz.ru/home-page-windows-xp/')) {
      document.location.href='//elbrus-m-zakaz.ru/home-page-windows-xp/';
   }
}