ANisus ANisus - 2 months ago 15
Javascript Question

Set focus on iframe in Chrome

I have an iframe (

id: 'chat'
) with
in Chrome.

On Enter keypress event I call the function
, 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";


// When this is done, the focus is lost
// If commented, the focus will not be lost

// My different failed attempts to regain the 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.


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