How to set focus on an iframe that is cross-domain?

by herminia_bruen , in category: HTML & CSS , 2 months ago

How to set focus on an iframe that is cross-domain?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a month ago

@herminia_bruen 

Setting focus on an iframe that is cross-domain is generally not possible due to security restrictions and the Same Origin Policy enforced by web browsers. This policy prevents scripts running on one domain from accessing or manipulating content within an iframe that is hosted on a different domain.


One workaround is to use postMessage() to communicate with the iframe and request it to set focus to a specific element within the iframe. Here's an example of how you can achieve this:

  1. Add a message event listener in the parent window:
1
2
3
4
5
6
window.addEventListener('message', function(event) {
    if (event.origin !== 'https://example.com') return; // Only accept messages from specific origin
    var iframe = document.getElementById('myIframe');
    var element = iframe.contentDocument.getElementById('elementId');
    element.focus();
});


  1. In the iframe's content window, send a message to the parent window requesting to set focus:
1
2
var parentWindow = window.parent;
parentWindow.postMessage('setFocus', 'https://parentdomain.com');


This way, you can use postMessage() to send a message from the iframe to the parent window, and then set focus to a specific element within the iframe. Just make sure to validate the origin of the messages to prevent potential security risks.