From 4b3ab1472c82d352ffe3b802de3007f90ceda628 Mon Sep 17 00:00:00 2001 From: Jonas Jenwald Date: Tue, 27 Jul 2021 09:25:36 +0200 Subject: [PATCH] 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. --- src/display/annotation_layer.js | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/display/annotation_layer.js b/src/display/annotation_layer.js index 94fcb105b..e5c4b7da5 100644 --- a/src/display/annotation_layer.js +++ b/src/display/annotation_layer.js @@ -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) {