Skip to content

Detect mobile browsers without user agent string parsing: Client Hints

ua-client-hints is a proposal to detect if a site is visited from Chrome on mobile.

It states By default, servers should receive only the user agent’s brand, significant version number, underlying platform name, and mobileness. Servers can opt-into receiving information about minor versions, the underlying operating system’s major version, and details about the underlying architecture, bitness and device model. The user agent can make reasonable decisions about how to respond to sites’ requests for more granular data. Browsers might even offer user-controlled settings to determine which hints or values should be allowed for some or all sites.

This piece of code is used to achieve this easily in Node.js.

const clientHintMobile = req.get('sec-ch-ua-mobile')
const isMobile = clientHintMobile
  ? clientHintMobile.includes('1') // values: ?1 or ?0
  : isMobileCheckUsingUserAgent(req.get('user-agent'))
console.log("isMobile --- " + isMobile);

In JavaScript,

const uaDataIsMobile = window.navigator.userAgentData?.mobile
const isMobile = typeof uaDataIsMobile === 'boolean'
  ? uaDataIsMobile
  : legacyIsMobileCheck(window.navigator.userAgent
console.log("isMobile --- " + isMobile);                        

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.