CosmicSeizure
CosmicSeizure

Reputation: 1514

Unity WebGL OnApplicationQuit()?

I need to remove player from database when he closes tab with WebGL game. I tried using OnApplicationQuit(), but that does not fire. Is there something similar that can be used for WebGL to call some logic when player closes the tab?

Upvotes: 0

Views: 2706

Answers (1)

CosmicSeizure
CosmicSeizure

Reputation: 1514

For anyone else who might struggle with this I solved it in a following way:

Inside WebGL template index.html i added this code ( SendMessage - https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html )

window.onbeforeunload = () => {
    unityInstance.SendMessage("CloseEvent", "CloseCallback");
    return "Are you sure to leave this page?";
}

in my case I put this code inside <script> after this code ( that's where unityInstance is assigned from above )

script.onload = () => {
            createUnityInstance
....

Important part for me was to have the return there, which shows alert window. That allows me to call database and make changes. Without the alert window the db call does not go through for some reason. Btw you can't change the text of the alert window unfortunately because of browser security changes. Hope this helps someone else in the future. Spent full day on this.

Upvotes: 1

Related Questions