Unity Web Request doesn't complete when called in onbeforeunload event

This is the onbeforeunload event. I created a jslib plugin where you can run some code on that event. I call it like this:

OnDestroyWebGL.subscribeToBeforeUnloadEvent();
OnDestroyWebGL.onbeforeunload += () => {
            Debug.Log("onbeforeunload");
            UnityWebRequest www = UnityWebRequest.Get("https://www.google.com");
            www.SendWebRequest();
};

If I check the developer tools, “onbeforeunload” is printed on the console when I attempt to close the tab. However, if I check the network tab, the http request won’t be sent until I cancel the “are you sure you want to close this tab” popup.

I am not sure if this is a bug or if it’s intended/normal behavior.

@brendanduncan_u3d can you shed some light on this matter? I checked this SO post, and people recommend using sendBeacon, but I was just hoping I could use UnityWebRequest for this.

I think this is a browser issue and not one UnityWebRequest can get around. If you try and make a small html test using XMLHttpRequest, it doesn’t work great when dealing with the timing of the beforeunload event, and syncronous XMLHttpRequest calls have been deprecated and crash from that event for the minimal testing I just did. sendBeacon is much lighter weight and seems to get sent within the timing requirements of beforeunload.

1 Like

Is there a Unity version of sendBeacon?

No, it’s not used by UnityWebRequest. You’ll have to add it with JS.

1 Like