Add a basic navigator polyfill for older Node.js versions

Modern Node.js versions now include a `navigator` implementation, with a few basic properties, that's actually enough for the PDF.js use-cases; please see https://nodejs.org/api/globals.html#navigator
Unfortunately we still support Node.js version `20`, hence we add a basic polyfill since that allows simplifying the code slightly.
This commit is contained in:
Jonas Jenwald 2025-04-28 12:52:42 +02:00
parent b47b248e15
commit 3d4e8bb17e
3 changed files with 23 additions and 27 deletions

View File

@ -67,6 +67,13 @@ if (isNodeJS) {
warn("Cannot polyfill `Path2D`, rendering may be broken."); warn("Cannot polyfill `Path2D`, rendering may be broken.");
} }
} }
if (!globalThis.navigator?.language) {
globalThis.navigator = {
language: "en-US",
platform: "",
userAgent: "",
};
}
} }
} }

View File

@ -643,30 +643,16 @@ class FeatureTest {
} }
static get platform() { static get platform() {
if ( const { platform, userAgent } = navigator;
(typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) ||
(typeof navigator !== "undefined" &&
typeof navigator?.platform === "string" &&
typeof navigator?.userAgent === "string")
) {
const { platform, userAgent } = navigator;
return shadow(this, "platform", {
isAndroid: userAgent.includes("Android"),
isLinux: platform.includes("Linux"),
isMac: platform.includes("Mac"),
isWindows: platform.includes("Win"),
isFirefox:
(typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) ||
userAgent.includes("Firefox"),
});
}
return shadow(this, "platform", { return shadow(this, "platform", {
isAndroid: false, isAndroid: userAgent.includes("Android"),
isLinux: false, isLinux: platform.includes("Linux"),
isMac: false, isMac: platform.includes("Mac"),
isWindows: false, isWindows: platform.includes("Win"),
isFirefox: false, isFirefox:
(typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) ||
userAgent.includes("Firefox"),
}); });
} }

View File

@ -19,13 +19,16 @@ if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
if ( if (
typeof PDFJSDev !== "undefined" && typeof PDFJSDev !== "undefined" &&
PDFJSDev.test("LIB") && PDFJSDev.test("LIB") &&
typeof navigator === "undefined" !globalThis.navigator?.language
) { ) {
globalThis.navigator = Object.create(null); globalThis.navigator = {
language: "en-US",
maxTouchPoints: 1,
platform: "",
userAgent: "",
};
} }
const userAgent = navigator.userAgent || ""; const { maxTouchPoints, platform, userAgent } = navigator;
const platform = navigator.platform || "";
const maxTouchPoints = navigator.maxTouchPoints || 1;
const isAndroid = /Android/.test(userAgent); const isAndroid = /Android/.test(userAgent);
const isIOS = const isIOS =