Skip to content

Instantly share code, notes, and snippets.

@amitsaxena
Last active October 18, 2019 21:51
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitsaxena/8601424 to your computer and use it in GitHub Desktop.
Save amitsaxena/8601424 to your computer and use it in GitHub Desktop.
CustomURL: Launch app if app is installed, else open an alternate URL (iOS all browsers)
<script type="text/javascript">
var timer;
var heartbeat;
var lastInterval;
function clearTimers() {
clearTimeout(timer);
clearTimeout(heartbeat);
}
window.addEventListener("pageshow", function(evt){
clearTimers();
}, false);
window.addEventListener("pagehide", function(evt){
clearTimers();
}, false);
function getTime() {
return (new Date()).getTime();
}
// For all other browsers except Safari (which do not support pageshow and pagehide properly)
function intervalHeartbeat() {
var now = getTime();
var diff = now - lastInterval - 200;
lastInterval = now;
if(diff > 1000) { // don't trigger on small stutters less than 1000ms
clearTimers();
}
}
function launch_app_or_alt_url(el) {
lastInterval = getTime();
heartbeat = setInterval(intervalHeartbeat, 200);
document.location = 'myapp://customurl';
timer = setTimeout(function () {
document.location = 'http://alternate.url.com';
}, 2000);
}
$(".source_url").click(function(event) {
launch_app_or_alt_url($(this));
event.preventDefault();
});
</script>
@matan23
Copy link

matan23 commented Sep 4, 2014

awesome

@cweekly
Copy link

cweekly commented Oct 15, 2014

In iOS8 Safari this doesn't seem to dodge the dreaded "invalid address" warning. Any updates or tips here would be fantastic. As far as I can tell, a reliable solution for this is not (yet?) known in the wider webdev community. It'd be a pretty valuable contribution, imho. Thanks in advance for any help! :)

@tildedave
Copy link

@cweekly Belatedly:

I am implementing this as its own page on my subdomain that is opened for the desired page with a normal a link that specifies target=_blank. The timeout then has a window.close() in it.

window.location.href = deepLink;

var now = new Date().valueOf();
setTimeout(function() {
    if (new Date().valueOf() - now < 100) {
        window.location.href = installAppLink;
    }

    window.close();
}, 1000);

This seems to get around the issues with 'invalid address' as the window will be automatically closed - users may still see it for a brief second. Also this isolates the awful ios hackery to one page on the site.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment