Set focus on iframe in Chrome

ANisus picture ANisus · Nov 13, 2011 · Viewed 16.9k times · Source

I have an iframe (id: 'chat') with designMode='on' in Chrome.

On Enter keypress event I call the function send(), which takes the iframe contents and writes it to a socket. My problem is that when clearing the iframe, I lose focus.

How to do I set the focus so I can continue to type text in the iframe?

function send(){
    var $iframe = $('#chat');
    var text = $iframe.contents().text() + "\n";  

    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);
}

I've tried many of the solutions on other questions, but none seems to work.

Answer

J. K. picture J. K. · Nov 13, 2011

The trick is to first set focus on the body and then create a Range.

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);