Search code examples
iosiphonesafariuser-agentios13

How to detect iOS 13 on JavaScript?


I use this function to detect iOS

export function isiOS() {
  return navigator.userAgent.match(/ipad|iphone/i);
}

is there any way to make it detected iOS13+? thanks

Why do I need it? usually, iOS safari can't download files therefore to make image downloadable I should render it as

<img src={qrImage} alt="creating qr-key..." />

however on Android/PC and pretty much everywhere else it's possible to do it directly via

<a href={qrImage} download="filename.png">
    <img src={qrImage} alt="qr code" />
</a>

so user just press image and download it. Turned on on iOS13 now second option works while first one doesn't anymore.


Solution

  • I would like to advice you against detecting operating system or browser from user agent, since they are susceptible to change more than an API for that does, till a reliable stable standard API lands. I have no idea about when this second part will happen.

    However, I can suggest to detect feature instead if in this case it is applicable to you.

    You can check if the anchor html element supports download attribute:

    "download" in document.createElement("a") // true in supporting browsers false otherwise

    That way you can display the appropriate html markup depending on the output for each case. Something like that may help:

    function doesAnchorSupportDownload() {
      return "download" in document.createElement("a")
    }
    // or in a more generalized way:
    function doesSupport(element, attribute) {
      return attribute in document.createElement(element)
    }
    
    document.addEventListener("DOMContentLoaded", event => {
      if (doesAnchorSupportDownload()) {
        anchor.setAttribute("display", "inline"); // your anchor with download element. originally display was none. can also be set to another value other than none.
      } else {
        image.setAttribute("display", "inline"); // your alone image element.  originally display was none. can also be set to another value other than none.
      }
    });
    

    For example, I use following to detect if I am on an ar quick look supporting browser on iOS:

    function doesSupportAnchorRelAR() {
      return document.createElement("a").relList.supports("ar");
    }
    

    You can also use techniques documented below: http://diveinto.html5doctor.com/detect.html#techniques