简体   繁体   中英

How to know if request is made with a mobile browser?

This question has been debated several times, so let me lay out the problem and see if I can get a clear and modern answer.

I have a file upload component, on a page, that will preview the file prior to ever sending it to the server. It supports multiple file types, including multiple image formats and pdf. I have 'alternative' views for certain scenarios, like 'tif' files can only natively be displayed in Safari.

My issue is embedding a PDF file. I have this working, no problem. Except in mobile. Mobile browsers don't support embedding PDF's.

So here's the core issue. I can display alternative text, with a download link. But I only want to do this in mobile browsers. I can't use media queries here, as this isn't really a screen size thing (and my core audience uses old, small desktop screens in clinic scenarios, which are about the size of a tablet in landscape mode).

I could use a UserAgent parsing approach, but these change, and browser support is shifting.

Then there's feature detection, but what works? Detecting touch support can be problematic.

So, what is the best approach for this scenario?

  1. fastest method is using JavaScript and detect what size is screen (px).

  2. you could do something like How to detect the device is an Android

 var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to detect if" + " the device is android phone."; function GFG_Fun() { var res = "Device is not Android Phone"; var userAgent = navigator.userAgent.toLowerCase(); var Android = userAgent.indexOf("android") > -1; if(Android) { res = "Device is Android Phone"; } el_down.innerHTML = res; }
 p#GFG_DOWN { color: green; font-size: 24px; font-weight: bold; } p#GFG_UP { font-size: 19px; font-weight: bold; } body { text-align: center; } h1 { color: green; }
 <body> <h1>GeeksForGeeks</h1> <p id = "GFG_UP"></p> <button onclick = "GFG_Fun()">click here </button> <p id = "GFG_DOWN"></p> </body>

Even so it is not 100% possible to detect if user uses android phone :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM