From 824a619a2a42175843006040ac3d124087a92896 Mon Sep 17 00:00:00 2001 From: Andrii Vitiv Date: Tue, 5 Nov 2024 19:01:56 +0200 Subject: [PATCH] Fix error on empty response headers Fixes https://github.com/mozilla/pdf.js/issues/18957 https://github.com/mozilla/pdf.js/pull/18682 introduced a regression that causes the following error: ``` Uncaught TypeError: Failed to construct 'Headers': Invalid name at PDFNetworkStreamFullRequestReader._onHeadersReceived (pdf.mjs:10214:29) at NetworkManager.onStateChange (pdf.mjs:10103:22) ``` The mentioned PR replaced a call to `getResponseHeader()` with `getAllResponseHeaders()` without handling cases where it may return null or an empty string. Quote from the [docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders#return_value): > Returns: > >A string representing all of the response's headers (except those whose field name is Set-Cookie) separated by CRLF, or null if no response has been received. If a network error happened, an empty string is returned. Run the following code and observe the error in the console. Note that the URL is intentionally set to an invalid value to simulate network error ```js ``` --- src/display/network.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/display/network.js b/src/display/network.js index 8ce4e1356cff6..9bf7aec9610db 100644 --- a/src/display/network.js +++ b/src/display/network.js @@ -273,15 +273,17 @@ class PDFNetworkStreamFullRequestReader { const fullRequestXhrId = this._fullRequestId; const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); + const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders(); const responseHeaders = new Headers( - fullRequestXhr - .getAllResponseHeaders() - .trim() - .split(/[\r\n]+/) - .map(x => { - const [key, ...val] = x.split(": "); - return [key, val.join(": ")]; - }) + rawResponseHeaders + ? rawResponseHeaders + .trim() + .split(/[\r\n]+/) + .map(x => { + const [key, ...val] = x.split(": "); + return [key, val.join(": ")]; + }) + : [] ); const { allowRangeRequests, suggestedLength } =