How to get focus back for parent window from an iframe programmatically in Javascript

15,182

Got the answer, now it works on all browsers

<script>
window.onload = function() {
    // blur the iframe
    document.getElementById("bing").blur();
    // set focus on #foo
    document.getElementById("foo").focus();
    // when iframe tries to focus, focus #foo
    document.getElementById("foo").onblur = function() {
        this.focus();
    };
};
</script>
<input id="foo" type="text" value="foo" /><br />
<iframe id="bing" width="800" height="500" src="http://wwww.bing.com" />
Share:
15,182
user1643156
Author by

user1643156

Updated on June 05, 2022

Comments

  • user1643156
    user1643156 almost 2 years

    Some websites have focus set on an element on window load. If I iframe that website, It seems not able to set focus on parent window, programmatically. This only happens to IE (9) and Firefox (19), Opera/Safari/Chrome are fine.

    <script>
    window.onload = function() {
        setTimeout(function() {
            // this does not focus #foo
            document.getElementById("foo").focus();
        // or more seconds that enough to see the iframe focus
        }, 3000);
    };
    </script>
    <input id="foo" type="text" value="foo" /><br />
    <iframe width="800" height="500" src="http://www.bing.com" />
    

    Does anyone know a workaround for this problem?