Prevent an iframe from stealing focus

2019-04-19 12:45发布

I have a website that embeds an iframe. When I was testing the iframe, I used google.com and noticed the search input field took focus. Clearly, I won't be using google.com for production but would like to prevent the iframe from stealing focus.

Is there a way to prevent an iframe from stealing focus?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-19 13:00

If you have access to server side scripting you can use it to download a live copy of the page you want to embed, search it and remove any focus stealing code, then display that modified page in your iframe. Or if you find there is no focus stealing code, you can just link your iframe to the remote page as usual.

Another option might be to initially hide the iframe with CSS style="display:none" and allow the user to unhide it with javascript Object.style.display="inline"

查看更多
干净又极端
3楼-- · 2019-04-19 13:12

Use a setTimeout function to refocus on an element of your choice, e.g. window.onload = function(){ setTimeout( function() { element.focus() }, 500 ) };

查看更多
仙女界的扛把子
4楼-- · 2019-04-19 13:15

I found a solution here:

Disable Body/Content Scrolling With jQuery - disableScroll

Disabling scrolling stopped the iframe from stealing the focus.

I used this in my jquery script:

if( $('iframe').length != 0 ) $(window).disablescroll();

window.addEventListener('touchstart', function onFirstTouch() 
{
window.removeEventListener('touchstart', onFirstTouch, false);
AllowScrolling()
}, false);

$(window).on("scroll",function(){ $(window).off("scroll"); AllowScrolling() });

setTimeout('AllowScrolling()',5000); //Fallback
function AllowScrolling(){$(window).disablescroll('undo')}

So if a user touches the screen or clicks the scroll bar, scrolling is permitted. Seemed to work ok for me.

查看更多
霸刀☆藐视天下
5楼-- · 2019-04-19 13:18

Not really. You can put the focus back on your window if the focus moves away (WARNING: I don't recommend using that code):

<body onblur="window.focus();">

This has some not so nice side-effects like not being able to focus the location bar in Firefox or getting into endless loops if the frame also tries to fight for the focus. So if you want to do this (that's a big "if", I don't recommend it) you should at least limit it to the page loading phase and allow the focus to be changed after that.

查看更多
登录 后发表回答