1

I'm trying to extend the native GamepadAPI to include custom controller code.

Using TypeScript, I implemented a simple function, to dispatch a "gamepadconnected" event.

    // simulate gamepadconnected event
    function dispatchGamepadConnectedEvent() {
        let gamepad = Object.create(Gamepad.prototype);
        console.log(gamepad);
        let event = new GamepadEvent('gamepadconnected', {
            gamepad: gamepad
        })
        window.dispatchEvent(event);
        console.log('Gamepad connect event dispatched.');
    }

However, when dispatching the event, I get an error:


GamepadĀ {}axes: (...)buttons: (...)connected: (...)id: (...)index: (...)mapping: (...)timestamp: (...)vibrationActuator: (...)__proto__: Gamepad

extension.ts:37 Uncaught TypeError: Failed to construct 'GamepadEvent': member gamepad is not of type Gamepad.
    at dispatchGamepadConnectedEvent (extension.ts:37)
    at extension.ts:48

Even though, the instantiated Gamepad object seems fine, the type of the Gamepad is not correct. Why is this like that? How can I create a new, proper Gamepad object to fire the native event?

Marco Klein
  • 191
  • 7

2 Answers2

0

You cannot create a native Gamepad object.

Object.create(Gamepad.prototype) does not create a Gamepad. It creates an object and sets it prototype to Gamepad.prototype. While this trickery often works for application-level APIs, it won't fool native browser APIs.

Your choices are:

  1. Pass null: {gamepad: null}
  2. Pass an actual gamepad reference {gamepad: navigator.getGamepads()[0]}
  3. Dispatch a CustomEvent, not a GamepadEvent.
  4. Try something else entirely.
Eejdoowad
  • 1,297
  • 9
  • 10
0

Not sure about the use case that's behind your question, but one alternative might be to use the WebHID API. I have recently used this API to create a Nintendo Joy-Con driver in JavaScript. If there happen to be reverse engineering efforts for your device in question (hint: check if there is a Linux driver), chances are that you can use this to talk to your device over WebHID.

DenverCoder9
  • 2,024
  • 11
  • 32