关于javascript:将重点放在Chrome中的iframe上

Set focus on iframe in Chrome

我在Chrome中有一个带designMode='on'的iframe(id: 'chat')。

在Enter键按下事件中,我调用了函数send(),该函数将iframe的内容写入到套接字中。 我的问题是,清除iframe时,我失去了焦点。

如何设置焦点,以便可以继续在iframe中键入文本?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function send(){
    var $iframe = $('#chat');
    var text = $iframe.contents().text() +"\
"
;  

    socket.send(text);

    // When this is done, the focus is lost
    // If commented, the focus will not be lost
    $iframe.contents().find('body').empty();

    // My different failed attempts to regain the focus
    //$iframe.focus();
    //$iframe.contents().focus();
    //$iframe.contents().find('body').focus();
    //$iframe.contents().find('body').parent().focus();
    //$iframe[0].contentWindow.focus();

    // I've also tried all the above with timers
    //setTimeout( function(){ $('#chat').contents().focus(); }, 100);
}

我在其他问题上尝试了许多解决方案,但似乎都没有用。


诀窍是先将焦点放在身体上,然后创建Range

1
2
3
4
5
6
var win = iframe.contentWindow;
var range = win.document.createRange();
range.setStart(win.document.body, 0);
range.setEnd(win.document.body, 0);
win.document.body.focus();
win.getSelection().addRange(range);


这个问题已经在这里回答

基本上,如果您不刷新iframe,则可以使用:

1
$iframe[0].contentWindow.focus();

请注意,我正在抓取基础iframe DOM对象。


我已经尝试过以下解决方案,它适用于所有浏览器(IE / Chrome / Firefox)

上下文:我想一直关注iframe。

1
2
3
4
5
    function IFocus() {
        var iframe = $("#iframeId")[0];
        iframe.contentWindow.focus();
    };
    window.setInterval(IFocus, 300);

希望它能对需要的人有所帮助...


我使用Chrome测试了该解决方案。我最初将其发布在"将焦点设置为iframe内容"中。

这是使用jQuery创建iframe的代码,将其附加到文档中,对其进行轮询,直到加载完毕,然后对其进行聚焦。这比设置一个任意超时更好,后者可能取决于iframe加载所需的时间,该超时可能有效也可能无效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var jqueryIframe = $('<iframe>', {
    src:"http://example.com"
}),
focusWhenReady = function(){
    var iframe = jqueryIframe[0],
    doc = iframe.contentDocument || iframe.contentWindow.document;
    if (doc.readyState =="complete") {
        iframe.contentWindow.focus();
    } else {
        setTimeout(focusWhenReady, 100)
    }
}
$(document).append(jqueryIframe);
setTimeout(focusWhenReady, 10);

用于检测何时加载iframe的代码改编自Biranchi对如何检查iframe是否加载或内容是否存在的答案。