Reputation:
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?
Upvotes: 3
Views: 3669
Reputation: 506
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);
}
Upvotes: 0
Reputation: 9020
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)
Upvotes: 1