• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Browser detection using the user agent

Serving different Web pages or services to different browsers is usually a bad idea. The Web is meant to be accessible to everyone, regardless of which browser or device they're using. There are ways to develop your website to progressively enhance itself based on the availability of features rather than by targeting specific browsers.

But browsers and standards are not perfect, and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. This document will guide you in doing this as correctly as possible.

Note: It's worth re-iterating: it's very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!

Considerations before using browser detection

When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. Start by trying to identify why you want to do it.

Look, or ask, in specialized forums: you're unlikely to be the first to hit this problem. Also, experts, or people with another point of view, can give you ideas for working around the bug. If the problem seems uncommon, it's worth checking if this bug has been reported to the browser vendor via their bug tracking system ( Mozilla ; WebKit ; Blink ; Opera ). Browser makers do pay attention to bug reports, and the analysis may hint about other workarounds for the bug.

Your site needs to use a specific Web feature that some browsers don't yet support, and you want to send those users to an older website with fewer features but that you know will work. This is the worst reason to use user agent detection because odds are eventually all the other browsers will catch up. In addition, it is not practical to test every one of the less popular browsers and test for those Web features. You should never do user agent sniffing. There is always the alternative of doing feature detection instead.

This is usually a bad practice, but there are some cases in which this is necessary. In these cases, you should first analyze your situation to be sure it's really necessary. Can you prevent it by adding some non-semantic <div> or <span> elements? The difficulty of successfully using user agent detection is worth a few disruptions to the purity of your HTML. Also, rethink your design: can you use progressive enhancement or fluid layouts to help remove the need to do this?

Avoiding user agent detection

If you want to avoid using user agent detection, you have options!

Feature detection is where you don't try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it's not, you use a fallback. In those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the API and determine how to use it from that. An example of feature detection is as follows. In 2017, Chrome unflagged experimental lookbehind support in regular expressions , but no other browser supported it. So, you might have thought to do this:

The above code would have made several incorrect assumptions: First, it assumed that all user agent strings that include the substring "Chrome" are Chrome. UA strings are notoriously misleading. Then, it assumed that the lookbehind feature would always be available if the browser was Chrome. The agent might be an older version of Chrome, from before support was added, or (because the feature was experimental at the time) it could be a later version of Chrome that removed it. Most importantly, it assumed no other browsers would support the feature. Support could have been added to other browsers at any time, but this code would have continued choosing the inferior path.

Problems like these can be avoided by testing for support of the feature itself instead:

As the above code demonstrates, there is always a way to test browser support without user agent sniffing. There is never any reason to check the user agent string for this.

Lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. Don't unintentionally use the API you are testing for in unsupported browsers. This may sound obvious and simple, but sometimes it is not. For example, in the above code snippets, using lookbehind in short-regexp notation (for example, /reg/igm) will cause a parser error in unsupported browsers. Thus, in the above example, you would use new RegExp("(?<=look_behind_stuff)"); instead of /(?<=look_behind_stuff)/ , even in the lookbehind supported section of your code.

This design technique involves developing your website in 'layers', using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in successive layers, each using more features.

This is a top-down approach in which you build the best possible site using all the features you want, then tweak it to make it work on older browsers. This can be harder to do, and less effective, than progressive enhancement, but may be useful in some cases.

Arguably the most common use and misuse of user agent sniffing is to detect if the device is a mobile device. However, people too often overlook what they are really after. People use user agent sniffing to detect if the users' device is touch-friendly and has a small screen so they can optimize their website accordingly. While user agent sniffing can sometimes detect these, not all devices are the same: some mobile devices have big screen sizes, some desktops have a small touchscreen, some people use smart TV's which are an entirely different ballgame altogether, and some people can dynamically change the width and height of their screen by flipping their tablet on its side! So, user agent sniffing is definitely not the way to go. Thankfully, there are much better alternatives. Use Navigator.maxTouchPoints to detect if the user's device has a touchscreen. Then, default back to checking the user agent screen only if (!("maxTouchPoints" in navigator)) { /*Code here*/} . Using this information of whether the device has a touchscreen, do not change the entire layout of the website just for touch devices: you will only create more work and maintenance for yourself. Rather, add in touch conveniences such as bigger, more easily clickable buttons (you can do this using CSS by increasing the font size). Here is an example of code that increases the padding of #exampleButton to 1em on mobile devices.

As for the screen size, use window.innerWidth and window.addEventListener("resize", () => { /*refresh screen size dependent things*/ }). What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effect can be easily achieved using CSS flexboxes , sometimes with floats as a partial fallback.

Also try to move less relevant/important information down to the bottom and group the page's content together meaningfully. Although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. Let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. Each box has an image, an overview, and a historical fun fact. The pictures are kept to a maximum reasonable size even on large screens. For the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. On a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. The boxes can be separated into multiple columns via two equally fair method. From this point on, we shall assume that all the dog boxes are at the top of the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. There a single instance of a dog box immediately above a cat box, of course. The first method uses horizontal Flexboxes to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. The second method uses a Column layout and resents all the dogs to the left and all the cats to the right. Only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multicolumns, resulting in a single column of very wide boxes on old browsers. Also consider the following. If more people visit the webpage to see the cats, then it might be a good idea to put all the cats higher in the source code than the dogs so that more people can find what they are looking for faster on smaller screens where the content collapses down to one column.

Next, always make your code dynamic. The user can flip their mobile device on its side, changing the width and height of the page. Or, there might be some weird flip-phone-like device thing in the future where flipping it out extends the screen. Do not be the developer having a headache over how to deal with the flip-phone-like device thing. Never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. The simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. If there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. Also note that there is a huge difference between the media queries (max-width: 25em) , not all and (min-width: 25em) , and (max-width: 24.99em) : (max-width: 25em) excludes (max-width: 25em) , whereas not all and (min-width: 25em) includes (max-width: 25em) . (max-width: 24.99em) is a poor man's version of not all and (min-width: 25em) : do not use (max-width: 24.99em) because the layout might break on very high font sizes on very high definition devices in the future. Always be very deliberate about choosing the right media query and choosing the right >=, <=, >, or < in any corresponding JavaScript because it is very easy to get these mixed up, resulting in the website looking wonky right at the screen size where the layout changes. Thus, thoroughly test the website at the exact widths/heights where layout changes occur to ensure that the layout changes occur properly.

Making the best of user agent sniffing

After reviewing all of the above better alternatives to user agent sniffing, there are still some potential cases where user agent sniffing is appropriate and justified.

One such case is using user agent sniffing as a fallback when detecting if the device has a touch screen. See the Mobile Device Detection section for more information.

Another such case is for fixing bugs in browsers that do not automatically update. Webkit (on iOS) is a perfect example. Apple forces all of the browsers on IOS to use Webkit internally, thus the user has no way to get a better more updated browser on older devices. Most bugs can be detected, but some bugs take more effort to detect than others. In such cases, it might be beneficial to use user agent sniffing to save on performance. For example, Webkit 6 has a bug whereby when the device orientation changes, the browser might not fire MediaQueryList listeners when it should. To overcome this bug, observe the code below.

Which part of the user agent contains the information you are looking for?

As there is no uniformity of the different part of the user agent string, this is the tricky part.

Browser Name and version

When people say they want "browser detection", often they actually want "rendering engine detection". Do you actually want to detect Firefox, as opposed to SeaMonkey, or Chrome as opposed to Chromium? Or do you actually want to see if the browser is using the Gecko or the WebKit rendering engine? If this is what you need, see further down the page.

Most browsers set the name and version in the format BrowserName/VersionNumber . But as the name is not the only information in a user agent string that is in that format, you can not discover the name of the browser, you can only check if the name you are looking for. But note that some browsers are lying: Chrome for example reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string, Chromium often reports itself as Chrome too or Seamonkey sometimes reports itself as Firefox.

Also, pay attention not to use a simple regular expression on the BrowserName, user agents also contain strings outside the Keyword/Value syntax. Safari & Chrome contain the string 'like Gecko', for instance.

[1] Safari gives two version numbers: one technical in the Safari/xyz token, and one user-friendly in a Version/xyz token.

Of course, there is absolutely no guarantee that another browser will not hijack some of these things (like Chrome hijacked the Safari string in the past). That's why browser detection using the user agent string is unreliable and should be done only with the check of the version number (hijacking of past versions is less likely).

Rendering engine

As seen earlier, in most cases, looking for the rendering engine is a better way to go. This will help to not exclude lesser known browsers. Browsers sharing a common rendering engine will display a page in the same way: it is often a fair assumption that what will work in one will work in the other.

There are three active major rendering engines: Blink, Gecko, and WebKit. As sniffing the rendering engines names is common, a lot of user agents added other rendering names to trigger detection. It is therefore important to pay attention not to trigger false-positives when detecting the rendering engine.

Rendering engine version

Most rendering engines put the version number in the RenderingEngine/VersionNumber token, with the notable exception of Gecko. Gecko puts the Gecko version number in the comment part of the User Agent after the rv: string. From Gecko 14 for the mobile version and Gecko 17 for the desktop version, it also puts this value in the Gecko/version token (previous version put there the build date, then a fixed date called the GeckoTrail).

The Operating System is given in most User Agent strings (although not web-focused platforms like Firefox OS), but the format varies a lot. It is a fixed string between two semicolons, in the comment part of the User Agent. These strings are specific for each browser. They indicate the OS, but also often its version and information on the relying hardware (32 or 64 bits, or Intel/PPC for Mac).

Like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. A technological survey must be in place to adapt the script when new browser versions are coming out.

Mobile, Tablet or Desktop

The most common reason to perform user agent sniffing is to determine which type of device the browser runs on. The goal is to serve different HTML to different device types.

  • Never assume that a browser or a rendering engine only runs on one type of device. Especially don't make different defaults for different browsers or rendering engines.
  • Never use the OS token to define if a browser is on mobile, tablet or desktop. The OS may run on more than one type of device (for example, Android runs on tablets as well as phones).

The following table summarizes the way common browser vendors indicate that their browsers are running on a mobile device:

In summary, we recommend looking for the string Mobi anywhere in the User Agent to detect a mobile device.

Note: If the device is large enough that it's not marked with Mobi , you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).

DEV Community

DEV Community

Timothy Huang

Posted on Jun 30, 2020

A simple way to detect if browser is on a mobile device with Javascript

Sometimes we need a little Javascript code snippet to detect if user use mobile device, the simplest way is detecting its browser user agent.

We use the regular expression test to detect if browser is a mobile device like:

demo is on codepen:

https://codepen.io/timhuang/pen/MWKEZMJ

https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device

Top comments (33)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

bechtold profile image

  • Joined Nov 27, 2020

Hey, this is very very unreliable. UserAgent can be changed and as far as I know, iPads want to be treated as desktops now and thus send the same UA in Safari as the Desktop Safari. Mozilla is of a similar opinion: developer.mozilla.org/en-US/docs/W... Hope that helps :-)

angelbearuk profile image

  • Location Florence, KY
  • Work Lifelong Student
  • Joined Sep 9, 2020

I didn't read your link, if you provided a solution using that link, my apologies. Otherwise, do you have a better solution? I'm thinking you do ;-)

That link shows that using UserAgent is unreliable. If you trust my comment you don't need to read the source :-)

In one of our projects, we have a workaround that checks for screen size, pixel density, touch and other features only available on mobile devices. It seems to work reliably, but it is an Angular module, that I can't share at the moment. Unfortunately, we don't have a plain JS solution yet. That's also the reason why I did search for a simpler way again (for a non-angular project) and found your solution. At first, I was amazed, but then I realized that we have tried this approach in the past and it was not reliable enough for what we needed. So I just wanted to leave this comment here, so people know about it. For this project, I'm back to simple breakpoints considering the width of the screen.

karlsnyder0 profile image

  • Joined Feb 26, 2021

"Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable."

If we require that users don't modify their UserAgent in order to use our website then the UserAgent is perfectly reliable!

jeancarlo13 profile image

  • Location Mexico
  • Work Software producto manager
  • Joined Apr 7, 2021

I agree with @bechtold , using the user agent is a bad idea, there are multiple features to consider, I recommend this article on how to use media queries in JavaScript, I think it is a bester practice.

"using the user agent is a bad idea, there are multiple features to consider"

Would you elaborate on why using the user agent is a bad idea? (Also, I'm not sure if you meant features or some other word.)

gabrielmlinassi profile image

  • Location Florianópolis - SC / Brazil
  • Work Newbie Web Developer at Freelancer
  • Joined Jan 4, 2020

@jeancarlo13 the problem with using media queries in JS is that it causes layout shift (FOUC) and it's a problem mainly on above-the-fold UI. Otherwise it's a good approach.

linehammer profile image

  • Location Dubai
  • Work Mr at mfc
  • Joined Aug 28, 2019

You can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query.

if (window.matchMedia("(max-width: 767px)").matches) { // The viewport is less than 768 pixels wide document.write("This is a mobile device."); }

You may also use navigator.userAgentData.mobile .

const isMobile = navigator.userAgentData.mobile;

Another approach would be a responsive media query. You could presume that a mobile phone has a screen size greater than x and less than y. For example:

@media only screen and (min-width: 320px) and (max-width: 600px) {}

net-informations.com/js/iq/default...

kouba profile image

  • Joined Sep 6, 2023

Unfortunately navigator.userAgentData.mobile appears to be not widely supported yet

caniuse.com/?search=userAgentData caniuse.com/?search=mobile

timhuang profile image

  • Location Taipei, TW
  • Work Developer at Deep Blue
  • Joined Jun 11, 2020

Thanks for sharing!

drgaud profile image

  • Location GLASGOW
  • Work Self employed at Glasgow
  • Joined Dec 30, 2019

Thank you for this, I have ended up placing it in a view class as a getter function

Honestly thanks for this eloquent regex test.

thanks for your improvement! :)

oskarcodes profile image

  • Location Zürich
  • Joined Feb 4, 2020

Make it shorter like this:

mitya profile image

  • Location Kyiv, Ukraine
  • Joined Jun 10, 2020

Wow, really short! Thanks for your improvement.

mk1331 profile image

  • Location Kazakhstan, Almaty
  • Joined Nov 24, 2021

Alternatively, you can use

navigator.mediaDevices.enumerateDevices().then(md => { console.log(md) }); and use field

MediaDeviceInfo.kind Read only Returns an enumerated value that is either "videoinput", "audioinput" or "audiooutput".

MediaDeviceInfo.groupId Read only Returns a DOMString that is a group identifier. Two devices have the same group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone.

That is, if several "videoinput" and their groupId are the same, most likely this is a mobile device, since there are more than one laptop and monitor with two cameras and more.

That function suported all desktop and mobile browsers except IE.

Great! An alternative solution. Thanks!

tgregoneil profile image

  • Joined May 23, 2020

'ontouchstart' in window => true for mobile devices => false for desktop environment

jdvivar profile image

  • Location London, UK & Madrid, Spain
  • Work Front-end web engineer at ING Bank
  • Joined Sep 17, 2019

Some desktops have touchscreen devices, this is not reliable

I think you've taken the question too literally. The main issue behind the question is for developers to distinguish whether their JavaScript code needs to handle touch events vs click events, and not to figure out if someone can literally lug their device around in a mobile manner. Determining if touch events are in the window object is a simple way to determine this. Cheers!

pursechartthere profile image

  • Joined Aug 31, 2023
I think you've taken the question too literally. The main issue behind the question is for developers to distinguish whether their JavaScript code needs to handle touch events vs click events

No, this is very often not true.

In my case, I'm interested in this right now because I need to default the UI rendering of a webpage to relate better to our mobile app when the user is on mobile.

If the user lands on a marketing page, for example, we want to frontload the marketing copy that talks about the mobile features of our product suite. That's not relevant to someone running Windows on a touchscreen laptop.

User Agent detection is not a recommended technique for modern web apps. There is a JavaScript API built-in for detecting media. The JavaScript window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. You can use this method to detect a mobile device based on the CSS media query.

$(document).ready(function(){ let isMobileDevice = window.matchMedia("only screen and (max-width: 760px)").matches; if(isMobileDevice){ // The viewport is less than 768 pixels wide //Conditional script here } else{ //The viewport is greater than 700 pixels wide alert("This is not a mobile device."); } });

You can use above script to do show/hide elements depending on the screen size.

net-informations.com/js/progs/mobi...

mehedilslamripon profile image

  • Location Bangladesh
  • Work Junior Software Developer
  • Joined Oct 21, 2020

This is working fine! Thank you.

Great! I hope this could help who need to detect if browser on a mobile device. Thanks for your visiting.

pro2stinger profile image

  • Joined May 1, 2022

it's better to use 'navigator.userAgentData.mobile' because it only returns true or false

ruslanstelmakh profile image

  • Joined May 18, 2022

unfortunately this property is not supported all browsers developer.mozilla.org/en-US/docs/W...

kak_kotyavo profile image

  • Education Yes 9 classes and college full.
  • Work Backend nodejs and php
  • Joined Apr 3, 2019

an interesting solution for new browsers, and most importantly fast: stackoverflow.com/questions/783868... ?

a pity that display media-queries are not available for very ancient devices and browsers (hello Safari)

for server side detect device in production, i use packet npmjs.com/package/node-device-dete... (I'm the author, maybe I'm PR late)

I have made some improvements to the speed of detecting devices and clients, if you also use the library, I recommend updating the dependency to the latest version.

Great! Thank you!

andreseduardop profile image

  • Joined Apr 11, 2021

It worked very well for me. Thanks, @timhuang I adapted the modification proposed by @drgaud

talha_rafiquee profile image

  • Joined Jan 3, 2021

hello, thank man, it helped me a lot. working like a charm.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

arjuncodess profile image

Next.js: The Future Of React?

Arjun Vijay Prakash - Mar 6

mirzaleka profile image

Learn how to document JavaScript/TypeScript code using JSDoc & Typedoc

Mirza Leka - Mar 3

fredabod profile image

A Simple CRUD app With GraphQL, Apollo Server, MongoDB, and Express

FredAbod - Mar 7

robertheory profile image

Simplificando IndexedDB

Roberto Costa - Mar 6

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

CodeWithAnbu

Detect Whether a Device is iOS or Not Using JavaScript

Detect Whether a Device is iOS or Not Using JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for developing dynamic and interactive web applications. Its versatility and ease of use have made it one of the most popular programming languages in the world. In this tutorial, we’ll explore how to use JavaScript to detect whether a device is running iOS or not.

Knowing the type of device your users are accessing your web application from is crucial as a software developer. This information can be used to provide a better user experience or to customize the layout and functionality of your web application. In this section, we’ll explore three different methods for determining if a device is running iOS using JavaScript:

User-Agent Detection

Navigator.platform detection, feature detection.

Each method has its own pros and cons, and it’s important for us to choose the right one for our specific use case. We’ll go over each method in detail, explaining how it works and providing code examples to help us implement it in our own projects.

One of the methods we can use to detect whether a device is running iOS or not is User-Agent Detection. This method involves examining the user-agent string of the device to determine the operating system and browser being used.

We can use the JavaScript navigator.userAgent property to retrieve the user-agent string and then check if it contains the word “iPhone”, “iPad”, or “iPod”. This method is simple to implement and can provide quick results, but it’s important to keep in mind that the user-agent string can be easily altered, making it not the most reliable method for detecting iOS devices.

Here’s an example of how to use the User Agent string to detect if a device is running iOS:

In the above code snippet, we are using the test() method of a regular expression to check if the string stored in the navigator.userAgent property contains any of the substrings “iPad”, “iPhone”, or “iPod”. The regular expression is surrounded by forward slashes (/) and is enclosed within the test() method.

If the test returns true, which means that the navigator.userAgent string contains one of the substrings, then we know that the device is running iOS and we print “This is an iOS device.” to the console and vice-versa.

Let’s say, for example, we run this code on an iPhone. The output would be:

And if we run this code on a device that is not running iOS, the output would be:

We can also determine if a device is running on iOS by checking the navigator.platform property. This property gives us a string value that represents the platform on which our browser is running. By evaluating this property, we can find out if our device is an iOS device or not. Essentially, we just have to check if the navigator.platform is equal to ‘iPad’, ‘iPhone’, or ‘iPod’, and if it is, then we know our device is an iOS device.

Here’s how we can use the navigator.platform property to detect if a device is running iOS:

In the above code snippet, we use of the navigator.platform property to detect if a device is running iOS or not. As we know, the navigator.platform property returns a string representing the platform on which the browser is running.

In this code, we’re checking if the navigator.platform is equal to ‘iPad’, ‘iPhone’ or ‘iPod’. If it is, we log the message “This is an iOS device.” to the console. Otherwise, we log the message “This is not an iOS device!” to the console.

It’s important to note that this method is not foolproof, as some non-iOS devices can have similar platform strings. However, this method is widely used and considered reliable in most cases.

Feature Detection is another method to determine if a device is running iOS or not. This method involves checking the availability of specific features that are unique to iOS devices. It involves checking for touch events, max touch points and other iOS specific functionalities to determine the device type.

For instance, the MaxTouchPoints property is used to determine the number of touchpoints supported by a device. If a device supports more than one touch point, it’s likely not running iOS. On the other hand, the ‘ontouchstart’ in window check is used to detect if a device has the ability to detect touch events. If this check returns true, it means the device is running iOS.

Let’s see how we can use feature detection to find out if the device is an iOS device or not.

The above code checks three specific properties: ontouchstart, navigator.MaxTouchPoints , and navigator.msMaxTouchPoints . If any of these properties exist in the current device, the code logs “This is an iOS device.” to the console. Otherwise, it logs “This is not an iOS device!”.

By checking these properties, we’re essentially checking if the device is touch-enabled, which is a common characteristic of iOS devices. However, it’s important to note that this method may not always be 100% accurate, as some non-iOS devices may also have touch capabilities. But overall, it’s a good starting point for feature detection in determining the type of device being used.

In this tutorial, we delved into the different ways to figure out if a device is running on iOS or not. We walked through the User-Agent detection method and talked about how it uses the navigator.userAgent property to identify the device type. Then, we went over the Navigator.platform detection method and how it checks the navigator.platform property to determine if the device is iOS.

We also touched upon the Feature Detection method, which involves checking for the presence of certain features that are only found on iOS devices. To wrap up, we provided examples of code to help illustrate how each method works.

How to detect iPad or iPhone web view via JavaScript?

  • Post author By John Au-Yeung
  • Post date May 21, 2022
  • No Comments on How to detect iPad or iPhone web view via JavaScript?

Labrador retriever puppy walking on green grass

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.

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

For instance, we write

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 .

Related Posts

Sometimes, we want to detect iPad Pro as iPad with JavaScript. In this article, we'll…

Sometimes, we want to detect Android phone via JavaScript. In this article, we'll look at…

Sometimes, we want to listen for scroll event for iPhone or iPad with JavaScript. In…

javascript detect safari on ios

By John Au-Yeung

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

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

Check for Mobile iOS Device in JavaScript

September 28, 2021 - 1 minute read

Here’s how you can check whether someone on your website or app is using a mobile iOS device in JavaScript:

A call to the ios() function will return true if the user is using an iPhone, iPad, or iPod. Otherwise, it will return false .

Link to this section Checking for iPhone usage

You could also check for a single device category. The below function will only return true for iPhone users:

Similarly, the iphone() function will return true if the user is using an iPhone, and it will otherwise return false.

Link to this section Conclusion

I’ve tried to make this snippet as precise as possible, but users can still fake their user agent header and so on.

Anyway, I hope you found this useful!

Instantly share code, notes, and snippets.

@carloscabo

carloscabo / is_ios_safari.js

  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • Solve Coding Problems
  • How to Check if an Object has a Specific Property in JavaScript ?
  • Difference between Ember.js and other traditional web applications
  • How to implement master-slave in CherryFramework in JavaScript ?
  • "Script error" reported in window.onerror without cross-site scripting
  • JavaScript Program to Check Prime Number By Creating a Function
  • How to Disable Submit Button on Form Submit in JavaScript ?
  • What is the use of curly brackets in the `var { ... } = …` statements ?
  • How to ignore loop in else condition using JavaScript ?
  • How to Set the Distance between Lines in a Text with JavaScript ?
  • JavaScript Program to Find All Factors of a Natural Number
  • JavaScript Program to Display Armstrong Number Between Two Intervals
  • How to Set Height Equal to Dynamic Width (CSS fluid layout) in JavaScript ?
  • JavaScript Program to Print Prime Numbers from 1 to N
  • How is Ajax different from JavaScript Libraries and Run Time Environments ?
  • What are the variable naming conventions in JavaScript ?
  • How to check for null, undefined or blank Variables in JavaScript ?
  • How to Change the Time Interval of setinterval() Method at RunTime using JavaScript ?
  • How to receive server-sent event notifications ?
  • JavaScript Program to Convert Farenheit to Celcius

How to detect the user browser ( Safari, Chrome, IE, Firefox and Opera ) using JavaScript ?

chrome-output

Please Login to comment...

author

  • JavaScript-Questions
  • Web Technologies
  • Google Maps testing a new feature that shows entrance to buildings
  • ChatGPT Gets a Voice: Introducing the New Read Aloud Feature
  • Meta Quest+ is Now Like Game Pass For Your VR Headset
  • MLB World Series Champions - Major League Baseball Winners List
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to Enable JavaScript on Apple Safari (iPad, iPhone iOS)

Are you having a hard time in trying to turn on JavaScript on your iPad or Apple iPhone device?

JavaScript has evolved into an essential tool that makes the web what it is today. It controls the dynamic elements of web pages, and most websites will fail to run correctly if your Apple Safari browser does not have its JavaScript enabled. Although disabling JavaScript offers browsers faster loading of a website, you should know that it reduces the overall browsing experience on your iPad or iPhone device.

Be it an iPhone 11, iPhone 10 or MacOS device, the steps in this guide will help you learn the simple process and benefits of enabling the JavaScript feature on your Safari browser.

Instructions for Web Developers

You may want to consider linking to this site, to educate any script-disabled users on how to enable JavaScript in six most commonly used browsers. You are free to use the code below and modify it according to your needs.

On enablejavascript.io we optimize the script-disabled user experience as much as we can:

  • The instructions for your browser are put at the top of the page
  • All the images are inlined, full-size, for easy perusing

We want your visitors to have JavaScript enabled just as much as you do!

What Is JavaScript and Why Do I Need It?

JavaScript is a type of code used by web developers to install and establish interactive content on websites – in essence, it allows web pages to dynamically load and send content in the background without page loads on your Apple Safari browser. Generally, JavaScript is used by modern websites to provide various features such as display advertisements – the reason why a small subset of internet users want it disabled.

However, disabling the JavaScript feature on your Safari web browser is much more of a hassle than it seems. If you turn off JavaScript on your browser, many websites won’t function properly. In most cases, you will also be unable to enjoy certain functions or view content that you are accustomed to accessing on JavaScript-based websites.

How to Enable JavaScript on Safari ​

Here’s how to turn on JavaScript on Safari:

1. Select the “Safari” icon on your home screen.

2. Scroll down the Settings page to find the menu item labelled “Safari”, and then select it.

3. Scroll to the bottom of the Safari menu and choose “Advanced” – choosing this will reveal the advanced settings for your Safari browser.

4. On the Advanced menu, find the option for enabling or disabling “JavaScript” for your Safari browser. On finding the JavaScript option, you’ll see a button next to it.

5. Now slide this button to the right to turn on JavaScript on your Safari browser.

6. That’s it! You’ve just enabled JavaScript.

How to Disable JavaScript on Safari ​

Here’s how to turn off JavaScript on Safari:

1. Tap on the “Settings” icon on your home screen.

5. Now slide this button to the left to turn off JavaScript on your Safari browser.

6. That’s it! You’ve just disabled JavaScript. ​

How to Enable JavaScript on Mac

Follow the steps below to activate JavaScript in Safari on Mac:

1. Open the Safari application by clicking on an icon that appears like a compass in your bottom toolbar.

2. Click on the “Safari” menu at the top left corner of the browser.

3. Under the Safari menu, find and click on “Preferences”. This will open a pop-up menu.

4. Move your cursor over to the “Security” tab and select it.

5. Now check the box beside “Enable JavaScript” to turn on JavaScript. Make sure the box is checked.

6. You can now close the “Preferences” window to apply your settings.

7. That’s it! You’ve enabled JavaScript.

8. Restart your browser.

How to Disable JavaScript in Safari on Mac

Follow the steps below to disable JavaScript in Safari on Mac:

2. Click on “Safari” menu at the top left corner of the browser.

3. Under the Safari menu, find and click on “Preferences”. This will open a dropdown menu.

4. Move your cursor over to the “Security” tab and then click on it.

5. Now uncheck the box beside “Enable JavaScript” to disable JavaScript.

7. That’s it! You’ve disabled JavaScript.

8. Restart your browser. 

Apple Safari comes built-in with a JavaScript engine that makes website elements interactive. And while it isn't actually necessary that you enable it to use your Safari browser, it's something that you'll perhaps want to do to enjoy a seamless browsing experience. Otherwise, many websites you visit will appear broken or won't even work.

JavaScript is enabled by default in Apple Safari, but you can verify if yours is active through the Safari tab. To do this, simply click on "Safari" at the top left of your screen to expand the Menu. Next, click on Preferences to reveal the Safari Preferences section. Now that you're in the Preferences section, find and click the "Security" tab to access the "Enable JavaScript" checkbox. If the checkbox has a tick symbol, it means JavaScript is active and working.

Millions of websites use JavaScript to display interactive elements, such as animations, special effects and more. If you browse them with JavaScript disabled in your Apple Safari, then you probably won't have the full experience that you normally would. Some JavaScript-based websites may appear dull or static, while others may not even work at all.

Olumide is a longtime writer who started his career as a digital marketer before transitioning into a copywriter almost eight years ago.

  • – Google Chrome
  • – Internet Explorer
  • – Microsoft Edge
  • – Mozilla Firefox
  • – Apple Safari

How to enable JavaScript in your browser and why http://www.enablejavascript.io/

How to enable JavaScript in your iPhone's Settings app to improve your Safari web experience

  • You can enable JavaScript on your iPhone in the Safari section of the Settings app. 
  • If JavaScript isn't turned on, many websites will appear broken in your Safari browser.
  • Though JavaScript should be enabled by default, it's important to check that it hasn't been accidentally disabled.

JavaScript is a popular programming language used by most websites.

On an iPhone , JavaScript should be turned on by default, but if it was disabled at some point, many websites will appear broken in the Safari browser. 

To enable JavaScript, go into the Settings app on your iPhone, click "Safari," then "Advanced," and swipe the JavaScript button to the right so it appears green. 

Here's a full breakdown with pictures.

Watch: Everything wrong with the iPhone

javascript detect safari on ios

  • Main content

iOS 17: How to Enable JavaScript on iPhone in Simple Steps

Enabling JavaScript on your iPhone running iOS 17 is a straightforward process. Head to the “Settings” app, tap “Safari,” and select “Advanced.” There you will find the JavaScript setting. Just switch it on, and voilà, JavaScript is now enabled on your iPhone.

After you complete this action, your mobile browser will be able to run JavaScript, which will greatly enhance your web browsing experience. Many websites use JavaScript for interactive features, so enabling it is crucial for a fully functional internet experience.

You can also watch this video about how to enable JavaScript on iPhone for additional info.

Introduction

So, you’ve just updated your iPhone to the latest iOS 17, and you’re excited to explore all the new features. But wait, you’re trying to play a game or use a feature on a website, and it’s not working. You scratch your head, wondering what could be wrong. Then it hits you – you need to enable JavaScript. But why is this important?

JavaScript is a programming language that makes web pages interactive. It’s like the secret sauce that adds functionality to websites – from refreshing your social media feed to playing online games, it’s the behind-the-scenes worker that makes it all happen. Without it, you’d be stuck in a world of static and boring web pages. And since we all use our iPhones for pretty much everything these days, from work to entertainment, having JavaScript enabled is a must. This tutorial is relevant to anyone who wants to make the most out of their iPhone’s browsing capabilities. Whether you’re a student, a professional, or just someone who loves to surf the web, this one’s for you.

Step by Step Tutorial on Enabling JavaScript on iOS 17

Before we jump into the steps, let’s understand what we’re trying to achieve here. By enabling JavaScript, you’re allowing your iPhone to execute JavaScript code on websites you visit, which will provide a richer browsing experience. Let’s get started!

Step 1: Open the Settings App

Open the “Settings” app on your iPhone.

The “Settings” app is your gateway to customizing your iPhone experience. It’s where you can adjust everything from your wallpaper to your privacy settings.

Step 2: Scroll and Tap on Safari

Scroll down and tap on “Safari,” which is Apple’s built-in web browser.

Safari is optimized for iOS, which means it’s designed to work seamlessly with your iPhone’s hardware and software.

Step 3: Tap on Advanced

Once in Safari settings, scroll down to the bottom and tap on “Advanced.”

The “Advanced” section is where you’ll find settings that are more technical, such as website data and debugging options.

Step 4: Toggle JavaScript On

In the “Advanced” section, you’ll see the “JavaScript” option. Toggle the switch to the right to turn it on.

When the switch is green, it means JavaScript is enabled. If it’s gray, that means it’s turned off.

Additional Information

Now that you’ve got JavaScript up and running on your iPhone, you might want to consider a few extra details. For starters, remember that not all websites are created equal. Some might not be optimized for mobile browsers, even with JavaScript enabled. Also, keep in mind that while JavaScript can make websites more interactive, it can also make them slower to load – especially if you’re on a slower internet connection.

If you’re concerned about security, you might want to be selective about where you enable JavaScript. Some websites might try to run harmful scripts, so it’s good to stay vigilant. You can always disable JavaScript for specific websites in the Safari settings under “Content Blockers.”

Remember, enabling JavaScript on iOS 17 should improve your web browsing experience, but it’s also important to use it wisely.

  • Open the “Settings” app.
  • Tap on “Safari.”
  • Tap on “Advanced.”
  • Toggle JavaScript to “On.”

Frequently Asked Questions

What is javascript.

JavaScript is a programming language used to create interactive elements on websites.

Why do I need to enable JavaScript on my iPhone?

Enabling JavaScript allows you to experience the full range of features on websites, like playing games or using web apps.

Can enabling JavaScript affect my iPhone’s performance?

Yes, it can impact battery life and data usage, but the effects are generally minimal.

Is it safe to enable JavaScript?

While there are some security risks, as long as you’re careful about which websites you visit, you should be fine.

How do I disable JavaScript if I need to?

You can disable JavaScript by following the same steps and toggling the switch to the left in the “Advanced” section of Safari settings.

Enabling JavaScript on your iPhone running iOS 17 is a breeze and opens up a world of interactive possibilities on the web. While it’s generally safe to have it turned on, remember to be mindful of the websites you’re visiting to avoid any security mishaps.

With JavaScript enabled, your iPhone is ready to take on any web challenge, whether it’s streaming videos, playing online games, or just browsing your favorite sites. Happy surfing!

Matthew Burleigh Solve Your Tech

Matthew Burleigh has been writing tech tutorials since 2008. His writing has appeared on dozens of different websites and been read over 50 million times.

After receiving his Bachelor’s and Master’s degrees in Computer Science he spent several years working in IT management for small businesses. However, he now works full time writing content online and creating websites.

His main writing topics include iPhones, Microsoft Office, Google Apps, Android, and Photoshop, but he has also written about many other tech topics as well.

Read his full bio here.

Share this:

Join our free newsletter.

Featured guides and deals

You may opt out at any time. Read our Privacy Policy

Related posts:

  • How to Enable Javascript on iPhone 14
  • How to Enable Javascript on an iPhone
  • How to Disable JavaScript on iPhone 15: A Step-by-Step Guide
  • 15 Ways to Fix Safari Not Working on iPhone in 2023
  • iOS 17 – How to Turn Off the iPhone Javascript Setting
  • Safari History iPhone: How to See It [2023 Guide]
  • 15 iPhone Settings You Might Want to Change
  • 3 iPhone Safari Tips You Might Not Know
  • Why Can’t I Create a Private Browsing Tab in Safari on My iPhone?
  • How to Turn Off Javascript on the iPhone 6
  • How to Get Safari Back on iPhone 13
  • How to Turn off Javascript on the iPad 2
  • How to Do Private Browsing on iPhone 15: A Step-by-Step Guide
  • How Do I Change Pop Up Blocker iPhone Settings in Chrome?
  • How to Clear Cookies on iPhone
  • How to Block Websites on iPhone 12: A Step-by-Step Guide
  • How to Bookmark on iPhone (2023 Guide)
  • How to Block All Cookies on iPhone 15: A Step-by-Step Guide
  • Can I Get Rid of Frequently Visited in Safari on iPhone?
  • How to Remove Frequently Visited on iPhone

COMMENTS

  1. javascript

    safari.pushNotification.toString() === '[object SafariRemoteNotification]'; Of course, the best way of dealing with browser-specific issues is always to do feature-detection, if at all possible. Using a piece of code like the above one is, though, still better than agent string detection. Share.

  2. Browser detection using the user agent

    Another such case is for fixing bugs in browsers that do not automatically update. Webkit (on iOS) is a perfect example. Apple forces all of the browsers on IOS to use Webkit internally, thus the user has no way to get a better more updated browser on older devices. Most bugs can be detected, but some bugs take more effort to detect than others.

  3. A simple way to detect if browser is on a mobile device with Javascript

    User Agent detection is not a recommended technique for modern web apps. There is a JavaScript API built-in for detecting media. The JavaScript window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string. You can use this method to detect a mobile device based on the CSS media query.

  4. How to Detect Mobile Browsers with JavaScript

    let isMobile = window.matchMedia("(any-pointer:coarse)").matches; Keep in mind that this only validates the query as true or false. A more refined way to check for mobile devices is to use media queries directly. let isMobile = window.matchMedia("only screen and (max-width: 480px)").matches;

  5. Detect Whether a Device is iOS or Not Using JavaScript

    JavaScript is a high-level, interpreted programming language that is widely used for developing dynamic and interactive web applications. Its versatility and ease of use have made it one of the most popular programming languages in the world. In this tutorial, we'll explore how to use JavaScript to detect whether a device is running iOS or not.

  6. How to detect iPad or iPhone web view via JavaScript?

    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.

  7. Detect a device is iOS or not using JavaScript

    In order to detect a device whether it is iOS or not. We're going to Navigator platform and Navigator userAgent property . Navigator userAgent property This property returns the value of the user-agent header which is sent by the browser to the server. Returned value, have information about the name, version, and platform of browser.

  8. Check for Mobile iOS Device in JavaScript

    This JavaScript snippet determines whether the user is using an iPhone, iPad, or iPod. This JavaScript snippet determines whether the user is using an iPhone, iPad, or iPod. ... Here's how you can check whether someone on your website or app is using a mobile iOS device in JavaScript: const ios = () ...

  9. javascript

    I would like to know what is the best way to detect if the browser is safari and also its version? I want to show something else if the browser is safari and its version is < 13. I was looking at different answers, but did not find a best answer. What I have so far is as below. But it seems it is not applicable to mobile and other things.

  10. JS Detect Safari on iOS devices · GitHub

    JS Detect Safari on iOS devices Raw. is_ios_safari.js This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters ...

  11. Detect Safari browser with pure CSS

    Define Safari using a media query. Neither Javascript nor server technology is needed. Works the same for macOS and iOS. In other words, for Apple des...

  12. Inspecting iOS and iPadOS

    Enabling inspecting your device from a connected Mac. Before you can connect your device to a Mac to inspect it, you must allow the device to be inspected. Open the Settings app. Go to Safari. Scroll down to Advanced. Enable the Web Inspector toggle. Now, connect the device to your Mac using a cable. In Safari, the device will appear in the ...

  13. How to detect the user browser ( Safari, Chrome, IE ...

    Detecting the Internet Explorer browser: The user-agent of the Internet Explorer browser is "MSIE" or "rv:". Both these values are passed to the indexOf() method to detect this value in the user-agent string and the result of both them are used with the OR operator.

  14. Detect iOS Safari back/forward gesture with JavaScript

    When the user goes back either via a back button or a browser gesture, I close the overlay by using an event listener window.addEventListener ("popstate", () => { showOverlay = false } Everything work's fine. But on iOS Safari, when the user swipes instead of using the back button, the overlay appears for like 1ms before closing.

  15. detect ipad/iphone webview via javascript

    16 Answers. This uses a combination of window.navigator.userAgent and window.navigator.standalone. It can distinguish between all four states relating to an iOS web app: safari (browser), standalone (fullscreen), uiwebview, and not iOS. userAgent = window.navigator.userAgent.toLowerCase(),

  16. How to Enable JavaScript on Apple Safari (iPad, iPhone iOS)

    Click on the "Safari" menu at the top left corner of the browser. 3. Under the Safari menu, find and click on "Preferences". This will open a pop-up menu. 4. Move your cursor over to the "Security" tab and select it. 5. Now check the box beside "Enable JavaScript" to turn on JavaScript.

  17. How to Enable JavaScript on Your iPhone in Safari

    To enable JavaScript, go into the Settings app on your iPhone, click "Safari," then "Advanced," and swipe the JavaScript button to the right so it appears green. Here's a full breakdown with pictures.

  18. iOS 17 Guide: How to Turn On JavaScript on iPhone

    Step 4: Toggle JavaScript on. Find the JavaScript setting and toggle the switch to the green ON position. By toggling this switch, you are enabling your Safari browser to process and display web pages that use JavaScript. After completing these steps, JavaScript will be enabled on your iPhone's Safari browser.

  19. javascript

    Detecting Browser and Its version. This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name. The data shown in the image above is not sufficient for detecting all the browsers e.g. userAgent of Firefox will have Fxios as a keyword rather than Firefox.

  20. iOS 17: How to Enable JavaScript on iPhone in Simple Steps

    Enabling JavaScript on your iPhone running iOS 17 is a straightforward process. Head to the "Settings" app, tap "Safari," and select "Advanced.". There you will find the JavaScript setting. Just switch it on, and voilà, JavaScript is now enabled on your iPhone. After you complete this action, your mobile browser will be able to run ...

  21. javascript

    Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only. When combined with navigator.platform === "MacIntel" iPad's are the only devices that define this property, therefore typeof navigator.standalone !== "undefined" filters out Macs running Safari (touchscreen or not).