How to detect if a link works?

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

I need to know if a link will open.

3条回答
  •  野趣味
    野趣味 (楼主)
    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.

提交回复
热议问题