How do I keep keyboard input focus on .js game when ads refresh?


#1

I have a website that hosts typing games (.js embedded into HTML). The game pages also have ads that refresh every minute. The refresh of the ads is causing keyboard function in many of my games to lose “focus” on the game (for example, someone typing can no longer type until they click on the game again).

Is there a way to keep the keyboard’s focus on the game?

I should note: The games are coded from HaXe and compiled into .js (HTML5)


#2

You could try setting stage.focus on each frame, though that would prevent the user from using another text input box on the page, perhaps on your site that would be fine, though


#3

Yeah, I do have a search field on the page. So that might inhibit the search function. I tried setting the div index to 0, but that didn’t work either. Just can’t find a solution on this one…


#4

Perhaps Event.ENTER_FRAME for setting stage.focus, unless you receive Event.ACTIVATE or Event.DEACTIVATE, though I suppose that works only when you leave the page.

Perhaps you could add a listener on the ad, so when it receives focus, you send focus back to the game? Troublesome that it steals focus like this :frowning:


#5

Sounds like I’ll need to ask my ad company to do that.

I’ve been on this one for weeks…

Are you referring to the game’s code or the page code for stage.focus?


#6

It might not work, but something sort of like:

var ad = document.getElementById ("my-advertiser");
var game = document.getElementById ("openfl-content");

ad.addEventListener ("focus", function (e) {
    e.preventDefault ();
    game.focus ();
});

…though it might be a little more nuanced, since there’s the hidden input text box that we use


#7

Thank you. I will try that and see if there is a difference.


#8

A hacky solution would be to steal focus every frame, but only if the mouse cursor is inside the game’s boundaries. Not sure that would work on mobile, since the “cursor” (a.k.a. the last known location of a tap) can teleport around, and you might not receive an event if it teleported out.

Another option is to use JavaScript to get the id of the current focused element. If it isn’t an id you recognize, then assume an ad stole focus and steal it back. The tough part would be updating your list of allowed ids whenever you updated the site. Actually, probably a better option would be to make a class (such as “valid-focus-target”) for it, since you can mark an unlimited number of elements as the same class. Then just check if the currently-focused element has the class “valid-focus-target.”


#9

Turns out, all I needed was:

var game = document.getElementById ("openfl-content");

game.focus ();

Sing to the rescue again. Thank man.