如果选项卡关闭,`fetch` 调用会继续吗?

Will a `fetch` call continue if the tab is closed?

浏览器现在提供 Fetch API,您可以像这样从 JavaScript 发出网络请求:

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();

如果用户在调用 fetch 和履行承诺之间关闭选项卡会怎样?浏览器会丢弃请求吗?如果在 unloadbeforeunload 事件中调用 fetch 怎么办?

我知道 sendBeacon 是用于此目的的 API 调用,但我想知道 sendBeacon 是否已过时,因为我们有 fetch

如果在触发它的JS环境消失时HTTP请求已经发送,那么它已经发送。

如果它在此之前消失,则不会发送请求。

如果在环境消失之前加载事件尚未触发,则永远不会调用事件处理程序。它不再存在了。

What if the call to fetch happens in the unload or beforeunload events?

那么,很有可能 JS 环境会在请求发送之前消失。

I know sendBeacon is the API call that is meant for this purpose

but I am wondering if sendBeacon is obsolete now that we have fetch.

没有

看看fetchkeepalive选项:

The keepalive option can be used to allow the request to outlive the page. Fetch with the keepalive flag is a replacement for the Navigator.sendBeacon() API.

这是一个例子:

fetch("/example", {keepalive: true});

与使用 navigator.sendBeacon 发送的请求相比,使用 fetchkeepalive 选项发送的请求具有更高的优先级。 fetch API 也更灵活并提供更多选项。如果没有keepalive,则无法保证用户关闭页面后请求将完成。

参考文献: