Matt
Matt

Reputation: 1257

Link redirect based on device

I have a link in an email going to a video at url xxx.xxxxxxx.xx/zzz, where zzz is a unique id for that video. I need to redirect the user based on their device to the right location. If they are coming from an iPhone, it will direct them to a deep link. Otherwise, direct them to the original url.

I have the following which will be in a page linked to from the email, but its not quite right:

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);
}

as a diagram:

email link -> device redirect -> if iphone || ipad {go to deep link} else go to video link

Upvotes: 0

Views: 182

Answers (2)

Matt
Matt

Reputation: 1257

So figure out the answer:

Have the original link in this format:

<html>
<a href="newsletter-redirect.html?video=http://xxx.xxxxxx.xx/mXp">Video</a>
</html>

and the newsletter-redirect.html page will have the following 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]);
}

This will redirect the user to the link http://xxx.xxxxx.xx/mXp if they are coming from a non-ios device.

Upvotes: 1

PC3TJ
PC3TJ

Reputation: 852

This should solve your problem. Dont forget that .match() uses a regular expression which requires escape characters. Then after you detect the iphone, ipod, ipad you just need to redirect using window.location property.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
    window.location="DEEPLINKURL";
  }else{
     window.location="LINKURL";
    }

Upvotes: 0

Related Questions