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
Provenance
- Commit
92ef60e- Tree
2108895- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
0f2e281
4 files changed+177 added−3 removed
modified:source/core/Ky.ts+4 added-2 removed
1184 unmodified lines1185 : (remainingTotal === undefined1186 ? this.#options.timeout1187 : Math.min(this.#options.timeout, remainingTotal));1188 1189+ // 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 });1197 1198 return this.#setResponseRequest(response, request);1199 } catch (error) {74 unmodified linesmodified:source/utils/timeout.ts+3 added-1 removed
22 unmodified lines232425262728292830313233343522 unmodified lines
reject(new TimeoutError(request)); }, options.timeout);
// Called unbound so a native `window.fetch` is not invoked with `options` as `this`, which throws "Illegal invocation" in browsers. // A synchronous throw rejects the promise, and `finally` still clears the timer so it cannot abort a later retry attempt. const {fetch} = options; options.fetch(request, init).then(resolve).catch(reject); fetch(request, init).then(resolve).catch(reject); }); } finally { clearTimeout(timeoutId); }}modified:test/browser.ts+39 added
632 unmodified lines633 await page.waitForTimeout(200);634 635 t.true(requestAborted, 'Request should be aborted on timeout');636 });637+638+defaultBrowsersTest('an unbound window.fetch works as the fetch option', async (t: ExecutionContext, page: Page) => {639+ let requestCount = 0;640+641+ server.get('/', (_request, response) => {642+ response.end('zebra');643+ });644+645+ server.get('/unicorn', (_request, response) => {646+ response.end('rainbow');647+ });648+649+ server.get('/flaky', (_request, response) => {650+ requestCount++;651+ if (requestCount === 1) {652+ response.sendStatus(500);653+ return;654+ }655+656+ response.end('recovered');657+ });658+659+ await page.goto(server.url);660+ await addKyScriptToPage(page);661+662+ // `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 */672+673+ t.deepEqual(results, ['rainbow', 'rainbow', 'rainbow', 'rainbow', 'recovered']);674+ t.is(requestCount, 2);675+});modified:test/fetch.ts+131 added
514 unmodified lines515 t.is(text, 'ok');516 t.is(requestCount, 2);517 t.false(retriedRequestSignalAborted);518 });519+520+test('the fetch option is called without a `this` value', async t => {521+ const thisValues: unknown[] = [];522+523+ 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();530+531+ t.is(text, 'ok');532+ t.deepEqual(thisValues, [undefined]);533+});534+535+test('the fetch option is called without a `this` value when timeout is disabled', async t => {536+ const thisValues: unknown[] = [];537+538+ 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();546+547+ t.is(text, 'ok');548+ t.deepEqual(thisValues, [undefined]);549+});550+551+test('the fetch option is called without a `this` value on retries', async t => {552+ const thisValues: unknown[] = [];553+554+ 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();561+562+ t.is(text, 'ok');563+ t.deepEqual(thisValues, [undefined, undefined, undefined]);564+});565+566+test('the fetch option is called without a `this` value on forced retries with a custom request', async t => {567+ const thisValues: unknown[] = [];568+569+ 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();585+586+ t.is(text, 'ok');587+ t.deepEqual(thisValues, [undefined, undefined]);588+});589+590+test('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+ });595+596+ 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+});599+600+test('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+ });605+606+ const api = ky.create({fetch: globalThis.fetch}).extend({retry: 0});607+ t.is(await api(server.url).text(), 'unicorn');608+});609+610+test('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+ });615+616+ t.is(await ky(new Request(server.url), {fetch: globalThis.fetch}).text(), 'unicorn');617+});618+619+test('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+ });624+625+ t.is(await ky(server.url, {fetch: globalThis.fetch, searchParams: {unicorn: 'rainbow'}}).text(), '/?unicorn=rainbow');626+});627+628+test('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+ });633+634+ t.is(await ky(server.url, {fetch: globalThis.fetch.bind(globalThis)}).text(), 'unicorn');635+});636+637+test('the fetch option inherited through ky.create() and ky.extend() is called without a `this` value', async t => {638+ const thisValues: unknown[] = [];639+640+ const api = ky.create({641+ async fetch(this: unknown) {642+ thisValues.push(this);643+ return new Response('ok');644+ },645+ }).extend({retry: 0});646+647+ t.is(await api(fixture).text(), 'ok');648+ t.deepEqual(thisValues, [undefined]);649+});