How to detect if a link works?

前端 未结 3 927
旧时难觅i
旧时难觅i 2021-02-02 01:49

I need to know if a link will open.

相关标签:
3条回答
  • 2021-02-02 02:28

    See Maximilian Hoffmann's answer for a more robust solution.


    An approach like this is common - hijack the timeout to redirect to a different URL. Would this approach work for you?

    <a id="applink" href="comgooglemaps://?q=Red+Lobster+Billings">Show map</a>
    
    <script type="text/javascript">
    
    var backup = "http://maps.google.com/?q=Red+Lobster+Billings";
    
    function applink(fail){
        return function() {
            var clickedAt = +new Date;
            setTimeout(function(){
                if (+new Date - clickedAt < 2000){
                    window.location = fail;
                }
            }, 500);    
        };
    }
    
    document.getElementById("applink").onclick = applink(backup);
    
    </script>
    
    0 讨论(0)
  • 2021-02-02 02:40

    The solution is adding an iframe with the URL scheme to your page. It silently fails if the app is not installed, so you need to check via a timer if opening the app worked or not.

    // detect iOS
    if (['iPhone', 'iPad'].indexOf(navigator.platform) > -1) {
    
      // create iframe with an Apple URL scheme
      var iframe = document.createElement('iframe');
      iframe.src = 'twitter://';
    
      // hide iframe visually
      iframe.width = 0;
      iframe.height = 0;
      iframe.frameBorder = 0;
    
      // get timestamp before trying to open the app
      var beforeSwitch = Date.now();
    
      // schedule check if app was opened
      setTimeout(function() {
        // if this is called after less than 30ms
        if (Date.now() - beforeSwitch < 30) {
    
          // do something as a fallback
    
        }
      });
    
      // add iframe to trigger opening the app
      document.body.appendChild(iframe);
      // directly remove it again
      iframe.parentNode.removeChild(iframe);
    }
    

    I wrote a post with a more detailed example that uses this approach to open the twitter app on iOS if installed.

    0 讨论(0)
  • 2021-02-02 02:47

    There isn't a way for you to know if a link will work but there is for Safari with something called Smart App Banners

    enter image description here

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="Google Maps" content="app-id=585027354"/> 
    </head>
    
    <body>
    The content of the document......
    </body>
    
    </html>
    

    What it basically does is checking if an app is installed. If it's not installed the user will be directed to the app store. If it's installed the user will be able to open the app from the website with the relevant data you'd be normally passing using the url scheme. You could use if for Google Maps.

    The down side of this is that it will only work on Safari but it's still better than nothing.

    0 讨论(0)
提交回复
热议问题