Why is my fetch keepalive call on page unload failing in Safari?

2.4k Views Asked by At

I need to send back a bit of data for reporting when the user closes or leaves a specific page. So I set up an API endpoint and am using window.fetch with the keepalive flag set to make sure that the call completes even if the page unloads completely.

The Javascript call in question looks like this:

async onLeavingPage() {
    (preparing data for call)
    const response = await fetch(
        (url),
        {
            keepalive: true,
            method: "POST",
            mode: "cors",
            headers: {
                "Content-Type": "application/json",
                Authorization: axios.defaults.headers.common["Authorization"]
            },
            body: JSON.stringify({})
        }
    );
    console.log(response);
}

I'm calling it by watching for the pagevisibility event and calling it when the page is hidden or terminated, using the page-lifecycle library.

lifecycle.addEventListener("statechange", (e) => {
            if (e.newState === "hidden" || e.newState === "terminated") {
                this.onLeavingPage();
            }
        });

The preferred behavior is for the call to be completed, even if the page is reloaded or another link is clicked on. But thanks to this CORS error, it's not happening. It works fine in Chrome and Firefox, but in Safari it fails with this error message in the console:

Fetch API cannot load (api endpoint) due to access control checks.

The same fetch call works in Safari if it's called in any other circumstance (like, say, clicking a link or minimizing and then maximizing the page), so it's something specific to calling it on page unload.

0

There are 0 best solutions below