Categories
JavaScript Answers

How to detect iPad or iPhone web view via JavaScript?

Spread the love

Sometimes, we want to detect iPad or iPhone web view via JavaScript.

In this article, we’ll look at how to detect iPad or iPhone web view via JavaScript.

How to detect iPad or iPhone web view via JavaScript?

To detect iPad or iPhone web view via JavaScript, we check window.navigator.userAgent and window.navigator.standalone.

For instance, we write

const standalone = window.navigator.standalone;
const userAgent = window.navigator.userAgent.toLowerCase();
const safari = /safari/.test(userAgent);
const ios = /iphone|ipod|ipad/.test(userAgent);

if (ios) {
  if (!standalone && safari) {
    //browser
  } else if (standalone && !safari) {
    //standalone
  } else if (!standalone && !safari) {
    //uiwebview
  }
} else {
  //not iOS
}

to get the user agent with window.navigator.userAgent

And window.navigator.standalone being false means that the page is opened in a web view in an app.

Then we check if the user agent is safari and ios with test.

We then check if the page is opened in ios. If it is then ios is true.

And then in the inner if block, we check for combinations of standalone and safari to see if it’s opened in a Safari web view.

If the page is opened in a web view, then !standalone && !safari is true.

Conclusion

To detect iPad or iPhone web view via JavaScript, we check window.navigator.userAgent and window.navigator.standalone.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *