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

后端 未结 2 762
小蘑菇
小蘑菇 2021-01-22 12:40

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 ha

相关标签:
2条回答
  • 2021-01-22 13:23

    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" />
    
    0 讨论(0)
  • 2021-01-22 13:25

    If I've read this correctly you just need to prevent the focus being shifted from the parent window to an element in the iframe.

    I would use an 'onfocus' trigger on the iframe element to switch the focus back to your page, like so:

    <iframe width="800" height="500" src="http://www.bing.com" onfocus="document.getElementById('foo').focus();"/>
    

    If (as I suspect you do) you only want to prevent the iframe stealing the initial focus onload but would like the user to be able to shift focus to it later, use a status variable, like so:

    <script type="text/javascript">
    var initialFocus = false;
    </script>
    
    <iframe width="800" height="500" src="http://www.bing.com" onfocus="if (initialFocus==false) { document.getElementById('foo').focus(); initialFocus = true; }"/>
    

    I hope this helps and I'm here if you have any questions.

    0 讨论(0)
提交回复
热议问题