How could I send a programmatic button click to a scene?

I would like to send a KeyboardEvent programmatically - basically because of testing.
Playground is

I am using

scene.getEngine().getRenderingCanvas().dispatchEvent(new KeyboardEvent('keydown',{'key':'Delete'}));

but it does not seem to work

Does anyone has an idea how to do it?

It is built into scene Interact with a Scene - Babylon.js Documentation

The page is about listening for events and about "By customizing the following code template you can control reactions within your scene to "

I would like to programmatically send an event to the scene.

By default the editor has the focus not the canvas. You need to set the focus onto the canvas


This clicks, but the event on line 26 is not received.

It does not output the actually kbInfo so it means the observer does not receive the event.

The focus() call is not in effect yet when the event is sent when doing in sequence: it seems you need to wait for a javascript tick between setting the focus and sending the event:



It works. Thank you @Evgeni_Popov @JohnK

Too soon. Too soon. I still can’t get it working in a test and cant reproduce it in the playground. Worst possible situation. Looking at it. I can see it is a problem with the focus because when setting the focus by hand (clicking the canvas) it works. But setting the focus in the code does not set the focus.

Ahh, the internet, we build, we love it and we pretty much hate it.

Turns out that you can not call canvas.focus(). You need to have element.tabIndex set to like element.tabIndex="-1" and only then you can set the focus. And I think I don’t need the timeout for the tick

      canvas.tabIndex = -1;
      canvas.dispatchEvent(new KeyboardEvent('keydown',{'key':'Delete'}))