Saturday 2 January 2021

How to send/dispatch keypress events to an embedded iframe in React?

I have an iframe of Google Slides which I embedded in my web app.
The iframe implementation is:

<iframe ref={slidesRef} src={src} width='100%' height='100%' allowFullScreen={true}/>

I want to listen to click events on the main web page (while the iframe is not necessarily in focus), then create their corresponding keypress events - and pass them to the iframe, thus making the slideshow iframe to trigger and react to the user key presses.

I tried something like this:

    function onButtonClick(e) {
        e.stopPropagation();
        slidesRef.current.focus();
        slidesRef.current.dispatchEvent(new KeyboardEvent('keypress', {
            key: 'ArrowRight', which : 39
        }));
    }

But it doesn't work - it only focuses on the iframe, but doesn't send the arrow key event.
I saw some solutions using the parent document inside the iframe or sending messages with postMessage, but I can't add any code inside my iframe since its origin is an external link.



from How to send/dispatch keypress events to an embedded iframe in React?

No comments:

Post a Comment