@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 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 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.