Skip to content

Instantly share code, notes, and snippets.

@DefiantBidet
Created April 2, 2013 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DefiantBidet/5293463 to your computer and use it in GitHub Desktop.
Save DefiantBidet/5293463 to your computer and use it in GitHub Desktop.
this is sample code to attempt to launch native applications from mobile browsers with a fallback to the html page if the native application is not installed on the users device. NOTE: this code sample is not DRY - and can be optimized. This is an amalgamation of several SO postings on the subject matter.
var clickedAt = +new Date(),
timeout, iframe, webURI, nativeURI;
// '+newDate()' is the equivalent of calling valueOf method
// of the Date Object. + is a unary operator.
// see: http://xkr.us/articles/javascript/unary-add/
if (navigator.userAgent.match(/Android/)) {
// Jelly Bean with Chrome browser
if (navigator.userAgent.match(/Chrome/)) {
// Jelly Bean with Chrome browser
setTimeout(function () {
if (+new Date() - clickedAt < 3000) {
// window.open( url , '_blank' );
window.location = webURI;
}
}, 2000);
window.location = nativeURI;
} else {
// Older Android browser
iframe = document.createElement("iframe");
iframe.style.border = "none";
iframe.style.width = "1px";
iframe.style.height = "1px";
timeout = setTimeout(function () {
// window.open( webURI , '_blank' );
window.location = webURI;
}, 1000);
iframe.onload = function () {
clearTimeout(timeout);
};
iframe.src = nativeURI;
document.body.appendChild(iframe);
}
} else if (navigator.userAgent.match(/iPhone|iPad|iPod/)) {
// IOS
timeout = setTimeout(function () {
if (+new Date() - clickedAt < 3000) {
window.location = webURI;
}
}, 2000);
clearTimeout(timeout);
window.location = nativeURI;
} else {
window.open(webURI, '_blank');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment