基于设备的链接重定向
问题描述:
我在电子邮件中链接到url xxx.xxxxxxx.xx/zzz上的视频,其中zzz是该视频的唯一ID。我需要根据用户的设备将用户重定向到正确的位置。如果他们来自iPhone,它将引导他们进入深度链接。否则,请将它们指向原始网址。基于设备的链接重定向
我有这将是从电子邮件链接到网页以下,但它并不完全正确:
var host = document.location.hostname + document.location.pathname;
if(navigator.userAgent.match("iPhone") || navigator.userAgent.match("iPad")){
deep link to redirect to here
}
else {
window.location.replace(host);
}
为图:
电子邮件中的链接 - >设备重定向 - >如果iphone || ipad {转到深层链接}否则转到视频链接
答
这应该可以解决您的问题。不要忘记.match()使用一个需要转义字符的正则表达式。然后,当你检测到iPhone,iPod,iPad你只需要使用window.location属性重定向。
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
window.location="DEEPLINKURL";
}else{
window.location="LINKURL";
}
答
于是想出了答案:
在这个格式原文链接:
<html>
<a href="newsletter-redirect.html?video=http://xxx.xxxxxx.xx/mXp">Video</a>
</html>
和通讯,将redirect.html页面将具有以下javascript:
var video = document.location.search.split("?video=");
if(navigator.userAgent.match("iPhone") || navigator.userAgent.match("iPad")){
window.location.replace("deep link code");
}
else {
window.location.replace(video[1]);
}
如果用户来自非ios设备,则会将用户重定向到链接http://xxx.xxxxx.xx/mXp。
我不确定** string.match **函数是这样工作的,它期望一个正则表达式。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – toskv
是的,绝对有效。 – Matt
是的。它返回一个数组,它应该足以通过truthyness测试。你得到的行为是什么?现在看起来,else分支会重新加载页面,导致代码再次执行,导致无限循环。 :d – toskv