So I have an iFrame that contains a form. I would like for the page to focus in on the input element "foo" when the page loads. Is there a way to do this?
-
Is that what you are after? http://stackoverflow.com/questions/369026/setting-focus-to-iframe-contents – Pav May 06 '11 at 01:46
-
no, im looking to focus on an element INSIDE the iframe, not the iframe itself – May 06 '11 at 01:50
-
1in the example above, you can use element id/name instead of `contentWindow` – Pav May 06 '11 at 01:54
2 Answers
if your iframe has src attribute with the same domain as the parent document then it is simple:
<iframe src=" ... " onload="document.getElementById('foo').focus();"></iframe>
but if not, then you have a problem with 'same origin policy':
1. if you have access to modify document inside iframe (I mean if you can add some javascript code there) it's a bit tricky but possible (here's a good article about that: http://softwareas.com/cross-domain-communication-with-iframes)
2. if you have a 3-rd party website inside your iframe then it is imposible
(the only way is to use some dns+document.domain tricks but they are extremely ugly)

- 8,700
- 12
- 62
- 83
-
In this wrong solution the document.getElementById('foo') is going to search in the parent page DOM, not in the child iframe – Gianpaolo Papa Feb 07 '23 at 14:22
Parent page cannot access directly an element on the DOM of an iframed page, so the only way to make this possible is using a way to communicate to the iframe from the parent page that it's required to put its focus on that element. And it will be the iframe page to make this operation.
So from the parent page you can send something like this
document.getElementById('iframeToCommunicateWith').contentWindow.postMessage({action: "give focus"});
<div style="height: 50px">This is the parent Page</div>
<iframe id="iframeToCommunicateWith" style="width: 100%; height: 100px;" src="./iframedocument.html" ></iframe>
Then on your iframe page you should have a function which will get the postmessage and trigger the focus on the form:
const useMessage = (evt) => {
if (evt.data.action === "give focus") {
document.getElementById("formElementToReceiveFocus").focus();
}
}
if (window.addEventListener) {
window.addEventListener("message", useMessage, false);
} else {
window.attachEvent("onmessage", useMessage);
}

- 458
- 4
- 9