HTML, how can i query document.visibilityState, and or listen to the visibilitychange event?

I’m wishing to trigger a function to pause my project (game) on the html target, whenever it’s obvious that the game isn’t being played. then unpause if the user returns to it.

In flash it used to be straighforward, listen to Event.DEACTIVATE, Event.ACTIVATE, the use of these events when compiling to the html target give mixed results, and in many browsers dont fire when you expect them too (e.g. minimising the browser / opening addition browser windows etc)

I’ve been directed by a html progrmmer to read up on the “Page Visibility API” , the visibilitychange event fires at obvious times, and document.hidden / document.visibilityState can be queried to discover the state of view of the game.

I’d really like to know how i could use this api, or query the document.visibility state within my code, as i’ve no idea how to reference the document directly from within openfl. any help greatly appreciated.

You can inject raw code with __js__.

So you can do:

untyped __js__ ("document.addEventListener(\"visibilitychange\", function() { console.log( document.visibilityState ); });");

It’s possible to expose haxe code to javascript: http://haxe.org/manual/target-javascript-expose.html

Don’t forget to wrap the special logic in #if html5 and #end.

1 Like

Or you can contribute :wink:

We could listen for more events in the Lime HTML5 backend, to dispatch window activate/deactivate events more reliably. This would help everyone :slight_smile:

many thanks Ibilon, i’ve worked with what you gave me to get to this

untyped __js__ ("document.addEventListener(\"visibilitychange\", $bind(this,this.handleVisibilityChange));");

and within my handleVisibilityChange function figured out i can query the state once it’s been copied to a var within openfl.

vstate = untyped __js__ ("document.visibilityState");

Whilst it would be great to be able to learn how to contribute to openfl, I’ve no idea how openfl works behind the scenes, I’d need to learn how github works too. I currently scrape by with little programming knowledge and good intentions, I bring things up on the forums i find that dont work, as i simply dont have the knowledge to know how to fix them ! (i’m not using the latest versions as my games dont work well with it either!)

It would just be an added event listener where you showed you (in the Lime source) but understood :slight_smile:

Hi, I have made pull request for this problem.