how to change focus out of IFrame

11,551

If you want to set the focus back to the outer window from inside the iframe, focussing the outer window itself is unlikely to give any visual feedback to the user, so it is better to focus a known form element in the outer page.

You can do this as follows:

outer.html

<html>
  <head>
    <title>Outer</title>
  </head>
  <body>
    <iframe id="iframe" src="inner.html">
    </iframe>
  </body>
</html>

inner.html

<html>
  <head>
    <title>Inner</title>
  </head>
  <body>
    <form id="innerForm">
      <input type="button" id="innerButton" value="Inner button" />
    </form>
  </body>
  <script type="text/javascript">
    // When we click the inner button...
    document.getElementById('innerButton').addEventListener('click', function() {
      /*
       * Do whatever you need to do here
       */

      // Focus the parent
      parent.focus();
    });
  </script>
</html>
Share:
11,551
paleozogt
Author by

paleozogt

Software Developer for Maxar. #SOreadytohelp

Updated on June 29, 2022

Comments

  • paleozogt
    paleozogt almost 2 years

    I have an IFrame with some buttons in it. When the buttons are clicked, the parent DOM is manipulated (it's all in the same domain, so don't worry about the same-origin policy).

    Since the user clicked on a button, the focus goes to the IFrame. However, I'd like to move the focus back to the parent document (mostly due to this FireFox problem).

    How can I do this?

    Edit: I've created a js-fiddle that shows the problem. While focus() seems to work if you call it on parent form elements, it doesn't work in general. As you can see from the js-fiddle there are no form elements in my parent document.