OnPause events for WebGL builds

Hello Meltdown.

Attach the following script to an object named MyObject:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class MyScript : MonoBehaviour {
  [DllImport("__Internal")]
  private static extern void registerVisibilityChangeEvent();

  void Start() {
    registerVisibilityChangeEvent();
  }

  void OnVisibilityChange(string visibilityState) {
    System.Console.WriteLine("[" + System.DateTime.Now + "] the game switched to " + (visibilityState == "visible" ? "foreground" : "background"));
  }
}

add the following /Assets/Plugins/visibilityChangeEvent.jslib plugin:

mergeInto(LibraryManager.library, {
  registerVisibilityChangeEvent: function () {
    document.addEventListener("visibilitychange", function () {
      SendMessage("MyObject", "OnVisibilityChange", document.visibilityState);
    });
    if (document.visibilityState != "visible")
      SendMessage("MyObject", "OnVisibilityChange", document.visibilityState);
  },
});

A small note:
One might assume that the game always starts in foreground, however, that is not always the case, because user can switch the browser tab while the game is still loading. In this case document.visibilityState can still be occasionally set to “hidden” at the time when your script starts, so you might want to explicitly notify your application about it at the time of event registration (see the plugin code above).

6 Likes