Skip to content

Instantly share code, notes, and snippets.

@amitsaxena amitsaxena/gist:8601424
Last active Oct 18, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

matan23 commented Sep 4, 2014

awesome

@cweekly

This comment has been minimized.

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

This comment has been minimized.

Copy link

tildedave commented Dec 31, 2014

@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
You can’t perform that action at this time.