google-chrome-extensiongamepadgamepad-api

Using gamepad-api via events, rather than polling


I am building a chrome extension that would enable the use of my 3d-mouse (made by 3d connexion) to scroll web pages. The built-in 3d connexion drivers are worthless, and the 3d mouse presents itself as a 2 button, 6 axis gamepad to the OS.

The implementation is currently working using the below method:

function get3DMouseData() {
    if (document.hasFocus()) {
        var gp = navigator.getGamepads()[0]
        // axis 5 controls scroll speed
        if (gp.axes[5]) window.scrollBy(0,Math.round(gp.axes[5]*10)*10)
    }
}

interval = this.setInterval(get3DMouseData, 50)

It doesn't seem to be the smartest strategy to run get3DMouseData 20 times por second, and an event-based implementation would probably be more efficient.

  1. Is there an event-based methods for the gamepad-api that I can use in the case above?
  2. This implementation does not work properly in certain sites (like gmail). What I am doing wrong?

Solution

  • There is no such events:

    Other events: More discussion needed, on whether to include or exclude axis and button changed events, and whether to roll them more together ("gamepadchanged"?), separate somewhat ("gamepadaxischanged"?), or separate by individual axis and button.

    Also it is said that proper polling is a best practice:

    Best Practice 1: Coordination with requestAnimationFrame() Interactive applications will typically be using the requestAnimationFrame() method to drive animation, and will want coordinate animation with user gamepad input. As such, the gamepad data should be polled as closely as possible to immediately before the animation callbacks are executed, and with frequency matching that of the animation. That is, if the animation callbacks are running at 60Hz, the gamepad inputs should also be sampled at that rate.

    Regarding gmail: I guess that it is due restriction policy set on that site:

    This specification defines a policy-controlled feature identified by the string "gamepad". Its default allowlist is 'self'.

    'self' The feature is allowed in documents in top-level browsing contexts by default, and when allowed, is allowed by default to same-origin domain documents in child browsing contexts, but is disallowed by default in cross-origin documents in child browsing contexts.

    https://www.w3.org/TR/gamepad/