Best approach to detect iPad Safari user

2019-04-01 19:05发布

问题:

What is the best approach to add code for detecting an iPad Safari user. I mean should we use 1. CSS (through link media..) 2. JS (through navigator object)

I have heard that using user-agent string is not the best way to detect iPad, because of inconsistencies.

Please suggest. Thank you.


I also have a follow-up question;

Actually the code to detect desktop/iPad is going to be part of JSP (and not static HTML files)...Now in my app, there are 200+ pages..So where exactly should I be adding the code for detection and how exactly should I add it? I mean do I have to update somewhere in the servlet web.xml file..

Sorry for mixing the 2 questions..But just added here as both are related questions..

回答1:

You always have iPad in the user-agent.

However, if you're targeting iPads so that you can show things differently, then CSS media queries are definitely the way to go forward.

See here how ZeptoJS detects iPad in JS.

To target iPad in both orientations, do this:

<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css">