Skip to content
Myr

Fix `fetch: window.fetch` throwing "Illegal invocation" in browsers

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The `fetch` option was invoked as a method of Ky's internal options object, so a native `window.fetch` passed as-is was called with that object as `this`. Chromium rejects this with "Failed to execute 'fetch' on 'Window': Illegal invocation" and WebKit with "Can only call Window.fetch on instances of Window". The function is now called unbound, which native fetch accepts.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 0f2e281 · Browse files · 4 files+177 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+177 added−3 removed

  • tests:+170 added−0 removed
  • other:+7 added−3 removed

4 files+177 added−3 removed

modified:source/core/Ky.ts+4 added-2 removed
1184 unmodified lines
1185 : (remainingTotal === undefined1186 ? this.#options.timeout1187 : Math.min(this.#options.timeout, remainingTotal));11881189 // Called unbound so a native `window.fetch` is not invoked with the options object as `this`, which throws "Illegal invocation" in browsers.1190 const {fetch} = this.#options;1191 const response = effectiveTimeout === undefined1190 ? await this.#options.fetch(request, nonRequestOptions)1192 ? await fetch(request, nonRequestOptions)1193 : await timeout(request, nonRequestOptions, this.#abortController, {1194 timeout: effectiveTimeout,1193 fetch: this.#options.fetch,1195 fetch,1196 });11971198 return this.#setResponseRequest(response, request);1199 } catch (error) {
74 unmodified lines
modified:source/utils/timeout.ts+3 added-1 removed
modified:test/browser.ts+39 added
632 unmodified lines
633 await page.waitForTimeout(200);634635 t.true(requestAborted, 'Request should be aborted on timeout');636});637638defaultBrowsersTest('an unbound window.fetch works as the fetch option', async (t: ExecutionContext, page: Page) => {639 let requestCount = 0;640641 server.get('/', (_request, response) => {642 response.end('zebra');643 });644645 server.get('/unicorn', (_request, response) => {646 response.end('rainbow');647 });648649 server.get('/flaky', (_request, response) => {650 requestCount++;651 if (requestCount === 1) {652 response.sendStatus(500);653 return;654 }655656 response.end('recovered');657 });658659 await page.goto(server.url);660 await addKyScriptToPage(page);661662 // `window.fetch` is intentional here since the bug only reproduces with a native fetch that checks its `this` value.663 /* eslint-disable unicorn/prefer-global-this */664 const results = await page.evaluate(async (url: string) => Promise.all([665 globalThis.ky(`${url}/unicorn`, {fetch: window.fetch}).text(),666 globalThis.ky(`${url}/unicorn`, {fetch: window.fetch, timeout: false}).text(),667 globalThis.ky(`${url}/unicorn`, {fetch: globalThis.fetch}).text(),668 globalThis.ky.create({fetch: window.fetch})(`${url}/unicorn`).text(),669 globalThis.ky(`${url}/flaky`, {fetch: window.fetch, retry: {limit: 1, backoffLimit: 0}}).text(),670 ]), server.url);671 /* eslint-enable unicorn/prefer-global-this */672673 t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'recovered']);674 t.is(requestCount, 2);675});
modified:test/fetch.ts+131 added
514 unmodified lines
515 t.is(text, 'ok');516 t.is(requestCount, 2);517 t.false(retriedRequestSignalAborted);518});519520test('the fetch option is called without a `this` value', async t => {521 const thisValues: unknown[] = [];522523 const text = await ky(fixture, {524 retry: 0,525 async fetch(this: unknown) {526 thisValues.push(this);527 return new Response('ok');528 },529 }).text();530531 t.is(text, 'ok');532 t.deepEqual(thisValues, [undefined]);533});534535test('the fetch option is called without a `this` value when timeout is disabled', async t => {536 const thisValues: unknown[] = [];537538 const text = await ky(fixture, {539 retry: 0,540 timeout: false,541 async fetch(this: unknown) {542 thisValues.push(this);543 return new Response('ok');544 },545 }).text();546547 t.is(text, 'ok');548 t.deepEqual(thisValues, [undefined]);549});550551test('the fetch option is called without a `this` value on retries', async t => {552 const thisValues: unknown[] = [];553554 const text = await ky(fixture, {555 retry: {limit: 2, delay: () => 0},556 async fetch(this: unknown) {557 thisValues.push(this);558 return new Response(thisValues.length < 3 ? 'error' : 'ok', {status: thisValues.length < 3 ? 500 : 200});559 },560 }).text();561562 t.is(text, 'ok');563 t.deepEqual(thisValues, [undefined, undefined, undefined]);564});565566test('the fetch option is called without a `this` value on forced retries with a custom request', async t => {567 const thisValues: unknown[] = [];568569 const text = await ky(fixture, {570 retry: {limit: 1, delay: () => 0},571 async fetch(this: unknown) {572 thisValues.push(this);573 return new Response('ok');574 },575 hooks: {576 afterResponse: [577 ({request}) => {578 if (thisValues.length === 1) {579 return ky.retry({request: new Request(request)});580 }581 },582 ],583 },584 }).text();585586 t.is(text, 'ok');587 t.deepEqual(thisValues, [undefined, undefined]);588});589590test('an unbound global fetch works as the fetch option', async t => {591 const server = await createHttpTestServer(t);592 server.get('/', (_request, response) => {593 response.end('unicorn');594 });595596 t.is(await ky(server.url, {fetch: globalThis.fetch}).text(), 'unicorn');597 t.is(await ky(server.url, {fetch: globalThis.fetch, timeout: false}).text(), 'unicorn');598});599600test('an unbound global fetch works as an instance default', async t => {601 const server = await createHttpTestServer(t);602 server.get('/', (_request, response) => {603 response.end('unicorn');604 });605606 const api = ky.create({fetch: globalThis.fetch}).extend({retry: 0});607 t.is(await api(server.url).text(), 'unicorn');608});609610test('an unbound global fetch works with a Request input', async t => {611 const server = await createHttpTestServer(t);612 server.get('/', (_request, response) => {613 response.end('unicorn');614 });615616 t.is(await ky(new Request(server.url), {fetch: globalThis.fetch}).text(), 'unicorn');617});618619test('an unbound global fetch works when searchParams rebuild the request', async t => {620 const server = await createHttpTestServer(t);621 server.get('/', (request, response) => {622 response.end(request.url);623 });624625 t.is(await ky(server.url, {fetch: globalThis.fetch, searchParams: {unicorn: 'rainbow'}}).text(), '/?unicorn=rainbow');626});627628test('a bound fetch still works as the fetch option', async t => {629 const server = await createHttpTestServer(t);630 server.get('/', (_request, response) => {631 response.end('unicorn');632 });633634 t.is(await ky(server.url, {fetch: globalThis.fetch.bind(globalThis)}).text(), 'unicorn');635});636637test('the fetch option inherited through ky.create() and ky.extend() is called without a `this` value', async t => {638 const thisValues: unknown[] = [];639640 const api = ky.create({641 async fetch(this: unknown) {642 thisValues.push(this);643 return new Response('ok');644 },645 }).extend({retry: 0});646647 t.is(await api(fixture).text(), 'ok');648 t.deepEqual(thisValues, [undefined]);649});