Skip to content

Commit

Permalink
Fix error on empty response headers
Browse files Browse the repository at this point in the history
Fixes #18957

#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
<script src="//mozilla.github.io/pdf.js/build/pdf.mjs" type="module"></script>

<script type="module">
  var url = 'blob:';

  pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.mjs';

  var loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise
    .then((pdf) => console.log('PDF loaded'))
    .catch((reason) => console.error(reason));

</script>
```
  • Loading branch information
CyberAndrii committed Nov 5, 2024
1 parent cefd1eb commit 824a619
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/display/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 } =
Expand Down

0 comments on commit 824a619

Please sign in to comment.