Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a link works?

Tags:

hyperlink

I need to know if a link will open.

like image 216
novicePrgrmr Avatar asked Jan 18 '14 04:01

novicePrgrmr


2 Answers

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>
like image 68
Aaron Brager Avatar answered Sep 27 '22 20:09

Aaron Brager


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.

like image 28
Max Hoffmann Avatar answered Sep 27 '22 22:09

Max Hoffmann