How to get focus back for parent window from an if

2019-02-26 17:44发布

问题:

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?

回答1:

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" />


回答2:

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.