0

I have a webpage with two iframes that each take up 50% of the screen.

<body>
    <div id="iframes">
        <iframe id="iframe1" src="https://example1.com"></iframe>
        <iframe id="iframe2" src="https://example2.com"></iframe>
    </div>
</body>

iframe1 has an event listener in it that is bound to the window and is listening for a keydown event. Basically it supports a keyboard shortcut for pressing the numpad+ key. I want this host html page to facilitate that keyboard shortcut so that if the user presses numpad+ while focused in iframe2 it will send the event to iframe1 and trigger the shortcut.

I can't get document.addEventListener("keydown") to trigger while focused inside iframe2. Also even if I get the event to trigger by clicking on the padding of the <body> tag... I get a CORS error when I use the dispatch event method to try and send the event to iframe1.

document.addEventListener("keydown", function(event) {
    if (event.code === "NumpadAdd") {
        console.log("key pressed");
        const el = document.getElementById("iframe1");
        el.contentWindow.dispatchEvent(event);
    }
});
Curtis
  • 3,170
  • 7
  • 28
  • 44
  • 1
    You cant access cross domain iframe's content https://stackoverflow.com/questions/9393532/cross-domain-iframe-issue – Jan Pfeifer Jan 31 '23 at 14:26
  • ok so if I add support for message sending to the webpage in iframe2 Ill be able to send it the event... but I still am not able to trigger the key event while focused on iframe1 – Curtis Jan 31 '23 at 15:34
  • If parent and first iframe are from same origin bind event listener from parent https://stackoverflow.com/questions/30397732/addeventlistener-to-iframe – Jan Pfeifer Feb 01 '23 at 07:30

0 Answers0