How to capture "esc" from an iframe?

Member

by addison , in category: HTML & CSS , 4 months ago

How to capture "esc" from an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 4 months ago

@addison 

To capture the "esc" key press event from an iframe, you can add an event listener to the document object in the iframe. Here's an example of how you can do this:

1
2
3
4
5
6
document.addEventListener('keydown', function(event) {
  if (event.key === "Escape" || event.keyCode === 27) {
    // Do something when the esc key is pressed
    console.log('Esc key pressed');
  }
});


This code snippet adds an event listener to the document object in the iframe that listens for the "keydown" event. When the event is triggered, it checks if the pressed key is the "Escape" key (modern browsers) or the key code 27 (older browsers). If the key is the "Escape" key, it will log a message to the console.


You can place this code inside a script tag within the iframe HTML document to capture the "esc" key press event within the iframe.