2

New to javascript here, I am messing around with using a gamepad while browsing (using gamepad API and TamperMonkey) and I am having trouble simulating to click a certain (x,y) coordinate on the screen. It reports "Cannot read property 'dispatchEvent' of null" and even when I console log my element inside the click function, it returns null. Can anyone help clarify where there could be a mistake?

(function() {
    'use strict';

    const rAF = window.mozRequestAnimationFrame || window.requestAnimationFrame;

    window.addEventListener("gamepadconnected", (event) => {
        console.log("A gamepad connected:");
        console.log(event.gamepad);
    });

    window.addEventListener("gamepaddisconnected", (event) => {
        console.log("A gamepad disconnected:");
        console.log(event.gamepad);
    });



    window.addEventListener('gamepadconnected',function(e) {
        updateLoop();
    })

    function updateLoop() {
        if(navigator.getGamepads) {
            var gp = navigator.getGamepads()[0];
          }

        const xboxButtonB = gp.buttons[1];
        const xboxButtonA = gp.buttons[0];

        
        if (xboxButtonA.pressed) {
            console.log('a pressed');
            click(1200,500);

        }

        if (xboxButtonB.pressed) {
            console.log('b pressed')
            click(700,500);
        }

        setTimeout(function () {
            rAF(updateLoop);
        }, 150);
    }

    
    function click(x, y){
        var ev = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': true,
                'screenX': x,
                'screenY': y
            });

            var el = document.elementFromPoint(x, y);
            console.log(el); //print element to console
            el.dispatchEvent(ev);
    }

})();
zaidsani
  • 21
  • 2

1 Answers1

0

e1 is null which means there's no element at the coordinates passed to elementFromPoint(). Note that the coordinates are relative to the top-left corner of the current viewport.

Try with click(0,0) and it should work since 0,0 is guaranteed to be inside the viewport.

nondebug
  • 761
  • 3
  • 5