Access navigator safely in the src/display/annotation_layer.js file

For code that's part of the core library, rather than e.g. the `web/`-folder, we should always be careful about *directly* accessing any DOM methods.
The `navigator` is one such structure, which shouldn't be assumed to always be available and we should thus check that it's actually present.[1]

Hence this patch re-factors the `navigator.platform` access, in the `AnnotationLayer`-code, to ensure that it's generally safe. Furthermore, to reduce unnecessary repeated string-matching to determine the current platform, we're now using a shadowed getter which is evaluated only once instead (at first access).

---
[1] Note e.g. the `isSyncFontLoadingSupported` getter, in the `src/display/font_loader.js` file.
This commit is contained in:
Jonas Jenwald 2021-07-27 09:25:36 +02:00
parent 777d890268
commit 4b3ab1472c

View File

@ -24,6 +24,7 @@ import {
AnnotationBorderStyleType,
AnnotationType,
assert,
shadow,
stringToPDFString,
unreachable,
Util,
@ -359,6 +360,15 @@ class AnnotationElement {
render() {
unreachable("Abstract method `AnnotationElement.render` called");
}
static get platform() {
const platform = typeof navigator !== "undefined" ? navigator.platform : "";
return shadow(this, "platform", {
isWin: platform.includes("Win"),
isMac: platform.includes("Mac"),
});
}
}
class LinkAnnotationElement extends AnnotationElement {
@ -539,10 +549,8 @@ class WidgetAnnotationElement extends AnnotationElement {
}
_getKeyModifier(event) {
return (
(navigator.platform.includes("Win") && event.ctrlKey) ||
(navigator.platform.includes("Mac") && event.metaKey)
);
const { isWin, isMac } = AnnotationElement.platform;
return (isWin && event.ctrlKey) || (isMac && event.metaKey);
}
_setEventListener(element, baseName, eventName, valueGetter) {