For Developers¶
Browser Class detects the browser twice, with two separate implementations:
- JavaScript (
js/browserclass.js, shipped minified asjs/browserclass.min.js) runs in the visitor's browser and adds the<body>classes. The librarybrowserclass/global-browserclassis attached to every page inhook_page_attachments_alter(). - PHP (
browserclass.module) runs on the server. It backs the tokens, thebrowserclass_get_classes()function, and thehook_browserclass_classes()hook.
flowchart LR
subgraph Browser
UA1[navigator.userAgent] --> JS[browserclass.min.js] --> Body["<body> classes"]
end
subgraph Server
UA2[User-Agent header] --> PHP["browserclass_get_classes()"]
Hook["hook_browserclass_classes()"] --> PHP
PHP --> Tokens["[browserclass:*] tokens"]
end
The two do not share code. A change to the detection rules has to be made in both
browserclass.module and js/browserclass.js. After changing the JavaScript, rebuild the minified
file; see Building the JavaScript.
browserclass_get_classes()¶
browserclass_get_classes(int $types = BROWSERCLASS_ALL): array
Returns the classes for the current request's user agent as an array of strings. Returns an empty
array when the request has no User-Agent header.
$types is a bitmask of these constants:
| Constant | Value | Adds |
|---|---|---|
BROWSERCLASS_BROWSER |
1 |
Browser classes, e.g. chrome, chrome140 |
BROWSERCLASS_PLATFORM |
2 |
One platform class, e.g. win |
BROWSERCLASS_MOBILE |
4 |
mobile or desktop |
BROWSERCLASS_OTHER_CLASSES |
8 |
Classes from hook_browserclass_classes() |
BROWSERCLASS_ALL |
15 |
All of the above |
// Browser and platform only.
$classes = browserclass_get_classes(BROWSERCLASS_BROWSER | BROWSERCLASS_PLATFORM);
The mobile check uses the classes collected before it. Leave out BROWSERCLASS_PLATFORM and it
can no longer use android, ipad and the like, which changes the result for some devices.
The function reads $_SERVER['HTTP_USER_AGENT'] and sets no cache metadata. If you render its
output, add the headers:User-Agent cache context yourself:
$build['#cache']['contexts'][] = 'headers:User-Agent';