DeviceRedirection
Logic to redirect links depending on device used
by jasonwilczak
HTML
<div>
<h2>
Device Selector:
</h2>
<button onclick="setDevice('android')">
Android
</button>
<button onclick="setDevice('iPhone')">
iOS
</button>
<button onclick="setDevice('desktop')">
Desktop
</button>
</div>
<div>
<h2>
This link should go to google
</h2>
<a href="https://www.google.com" target="_blank">Test Non-Affected Link</a>
<h2>
This link should go to your device of choice link or msn.com
</h2>
<a href="https://www.msn.com" target="_blank">Test Redirect Link</a>
</div>
JavaScript
window.onclick = function(e) {
if(!e || !e.target || e.target.tagName != 'A') return true;
var redirectUrl = e.target;
var device = getMobileOperatingSystem();
var isWorkDayLink = checkIfLinkIsWorkday(redirectUrl);
if(isWorkDayLink) {
var appUrl = DetectAndServe();
redirectUrl = appUrl || redirectUrl;
}
//alert for demo purposes only
alert(' Device Identified: '+device+ '\n Is WorkDay Link: '+isWorkDayLink+'\n Final Destination: '+redirectUrl);
window.open(redirectUrl);
};
function checkIfLinkIsWorkday(url) {
if (/msn/i.test(url)) {
return true;
}
return false;
}
function DetectAndServe(){
if (getMobileOperatingSystem() == "android") {
return "https://developers.google.com";
}
if (getMobileOperatingSystem() == "ios") {
return "https://developers.apple.com";
}
return null;
};
function getMobileOperatingSystem() {
//window.deviceOverride is for testing only - do not use in final solution
var userAgent = window.deviceOverride || navigator.userAgent || navigator.vendor || window.opera;
// Windows Phone must come first because its UA also contains "Android"
if (/windows phone/i.test(userAgent)) {
//no windows phone app - use web link
return "desktop";
}
if (/android/i.test(userAgent)) {
return "android";
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "ios";
}
return "desktop";
}
window.setDevice = function(deviceOverride) {
//This function is only illustration purposes and should not be used in the final solution
window.deviceOverride = deviceOverride;
console.log('deviceOverride set:'+window.deviceOverride);
}