When attempting to register a custom Gamepad class using GamepadEvent, the conversion of the value to 'Gamepad' has failed

I have been working on developing a virtual controller in the form of a Gamepad class and registering it. Currently, my implementation is essentially a duplicate of the existing Gamepad class:

class CustomController {
    readonly axes: ReadonlyArray<number>;
    readonly buttons: ReadonlyArray<GamepadButton>;
    readonly connected: boolean;
    readonly hapticActuators: ReadonlyArray<GamepadHapticActuator>;
    readonly id: string;
    readonly index: number;
    readonly mapping: GamepadMappingType;
    readonly timestamp: DOMHighResTimeStamp;

    constructor() {
        this.axes = [];
        this.buttons = [];
        this.connected = true;
        this.hapticActuators = [];
        this.id = "custom-id";
        this.index = 200;
        this.mapping = "standard";
        this.timestamp = Math.floor(Date.now() / 1000);
    }
}

To implement it, I used the following code:

const event = new GamepadEvent("gamepadconnected", {
    gamepad: new CustomController() as Gamepad
})
window.dispatchEvent(event);

However, an error message pops up stating:

Failed to construct 'GamepadEvent': Failed to read the 'gamepad' property from 'GamepadEventInit': Failed to convert value to 'Gamepad'.
TypeError: Failed to construct 'GamepadEvent': Failed to read the 'gamepad' property from 'GamepadEventInit': Failed to convert value to 'Gamepad'.

Seeking solutions: How can I successfully create and register my own custom Gamepad class with a GamepadEvent?

Answer №1

The browser requires an actual game controller, not just any object resembling one.

If you need to simulate a game controller for testing purposes, here are some suggestions:

  1. Suspend disbelief. Instead of convincing the browser there's a real game controller, you can simply imagine it in your code. This way, your code operates as if there is a game controller present without involving the browser.

     const myFakeGamepad = new MyJoystick();
    
     // Instruct your code to utilize the fake game controller
     navigator.getGamepads = function(){
       return [myFakeGamepad];
     };
    
  2. Utilize a framework: There are resources available that allow you to simulate user input, such as a game controller. One recommended tool is puppeteer, which uses a web browser to mimic actions like button presses.

  3. Advanced method: Modify the browser's code. While unconventional, you could potentially alter the browser's code to recognize your faux game controller. However, this approach may be excessive and require substantial effort.

Overall, opting for the first suggestion is likely the most practical choice.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

"Utilize the handle property of a component when interacting with the window.onclick

In my component, I have a property called enableButtons which is set to true when I click on an ion-menu label. However, I want this property to revert to false if I click anywhere else. Here's the code I tried: export class ProfilePage implements OnI ...

Identifying Flaws in Components during Creation with Ready-Made spec.ts Files

Currently, I have embarked on the journey of creating unit tests for my Angular Material project. At the moment, my focus is on testing whether the pre-made spec.ts files for each component are passing successfully. Despite the fact that my project compile ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

Having difficulty executing JavaScript code from the VB code behind

Recently, I have encountered a strange issue while working with ASP/VB.net. In my code behind VB file, I am trying to call a JavaScript function, but it seems like nothing is happening. Surprisingly, I have used a very similar method on several other pages ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Tips for displaying a close icon after completing a file upload

I need to implement a feature where once a user uploads a file, a cross sign should be enabled on the file. I attempted to use javascript for this functionality, but it seems to not be working as expected. There are more than 8-10 different file types that ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Unique Input Values in Forms

I'm encountering an issue with a basic HTML form connected to a PHP script for processing values. Despite thorough testing, the form is not functioning correctly. Upon inspecting the form markup, I discovered: <form id="delete_item_3_form" action ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

Using event.target to pass HTML form data to FormData is causing an error stating that the Argument of type 'EventTarget' cannot be assigned to a parameter of type 'HTMLFormElement'

Looking to extract data from a form and store it in FormData: const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); const value = formData.get(' ...

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Identify input elements that specifically contain an onclick event

Several of the input elements on my page have a function called setSomeFunction() that either shows or hides certain divs when clicked. I know I can locate all the input elements using document.getElementsByTagName("input") and store them in an array. How ...

JavaScript - continuously update the image marked as "active"

I have a collection of 4 pictures that I want to rotate through in my web application. Each picture should have the "active" class applied to it, similar to when you hover over an image. .active, .pic:hover{ position: absolute; border: 1px solid ...

AngularJS - Smoothly navigate to the top of the page by swiping left or right

I'm currently working on a project in angularJS and ionic that involves a slidebox with three slides, each containing different content. My goal is to scroll back to the top every time I switch between slides. Initially, I thought using on-swipe-left ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...

Having trouble with the password strength indicator in React-redux?

Hey there, I'm currently working on implementing a progress strength bar for password validation in React. While I've made progress with the code to check the password regex, I'm struggling to understand how to incorporate the password stren ...

Having trouble getting the vue-slick-carousel to function properly when using it from the CDN

Struggling to implement a small app using the CDN script at , but so far no success. I'm a novice with vue.js and unsure if I need to import anything. According to the documentation, importing is required: Vue-slick-carousel Following this structure ...

How can we eliminate the 'www' in a URL using NodeJS and Express?

What is the best way to eliminate the 'www' in a URL using NodeJS + Express? For instance, when a client connects to , how can we automatically redirect them to without the 'www'? ...