Search Unity

[WebGL] catch close window button

Discussion in 'Web' started by Gushus, Nov 26, 2015.

  1. Gushus

    Gushus

    Joined:
    Jun 6, 2015
    Posts:
    2
    Hej

    Is there a way to catch the event of a clicked close-window button?
    I already tried:
    Code (JavaScript):
    1. <script>window.onbeforeunload = function() { return "Sure?"; }</script>
    On Top / Bottom of the 'index.html' - did'nt work
    Code (CSharp):
    1. public void OnApplicationQuit() { Application.ExternalEval("..") }
    - didn't work

    I would need some sort of a "Do you really want to leave?" Dialog if the user wants to close the popup where my WebGL content is running.

    I'm looking forward for your answers as I'm already starting to get depressions.. ^^

    Have a nice day!
    Gushus
     
  2. NocturnalWisp

    NocturnalWisp

    Joined:
    Oct 2, 2019
    Posts:
    62
    Hey,

    I know this question is very old, and I'm not sure if this solution works on that date or wasn't implemented in the engine yet, but I figured that I would share my solution in case it help those coming across this question.

    The way I solved this for work is as follows; I created a jslib file that can run Java Script and interface with unity using emscripten. The format for this file can be found here: Unity - Manual: WebGL: Interacting with browser scripting (unity3d.com)

    I created a new function in the jslib called Initialize that I call within a monobehaviour. (See the same documentation for how to call the functions) I then handled the close window event. You can adjust this to how you like even setting a way to make the application "Dirty" and only showing the message when the user has changed something. Here is the function I made:


    Code (JavaScript):
    1.     Initialize: function() {
    2.         window.onbeforeunload = function() {
    3.            return "Are you sure you really want to leave the application?";
    4.         };
    5.     },
    I know that the javascript code block isn't for this, but I used it anyway. :p

    Hopefully this helps the next person who is getting super annoyed with the webGL stuff.