Determine an installed app using Safari on iPhone

2019-04-02 16:58发布

问题:

I would like to determine an installed app using custom URL scheme on iPhone Safari.

You may believe it is impossible to do this, but JavaScript helped me to figure this out.

  <script>(function(){

var fallbackLink = '<?=$info['failed_url']?>'+window.location.search+window.location.hash;

var isiOS = navigator.userAgent.match('iPad') || navigator.userAgent.match('iPhone'),
    isAndroid = navigator.userAgent.match('Android');

if (isiOS || isAndroid) {
  document.getElementById('loader').src = '<?=$info['scheme']?>://'+window.location.search+window.location.hash;

  fallbackLink = isAndroid ? '<?=$info['failed_url']?>' :
                             '<?=$info['failed_url']?>' ;
}
window.setTimeout(function (){ window.location.replace(fallbackLink); }, 1000);

})();</script>

here is my script.

I already know custom URL scheme of the iPhone application. It successfully launches the application if it exists on the iPhone. However, if the iPhone doesn't have the application, it redirects to a different page.

I put certain code on the failed web page to notice that user doesn't have the application. My plan was perfect until I found this.

The JavaScript redirection works even though the application is launched on iPhone after timeout.

Is there a way to stop JavaScript if iPhone launched application?

Thank you.

回答1:

You can always cancel the timeout when the window loses focus.

var countdown = window.setTimeout(function (){
    window.location.replace(fallbackLink);
}, 1000);

window.addEventListener("blur", function (){
    window.clearTimeout(countdown);
}, false);