Set focus on iframe in Chrome

17,665

Solution 1

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

Solution 2

This question has been answered here

Basically, if you are not refreshing the iframe you could use:

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

Note that I'm grabbing the underlying iframe DOM object.

Solution 3

I have tried below solution it works in all browser (IE/Chrome/Firefox)

Context: I want to focus the iframe all the time.

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

Hope it helps, if any one in need...

Share:
17,665
ANisus
Author by

ANisus

Starting with C64 basic in my childhood, going through Atari's STOS, Amiga's AMOS, Motorola 680x0 assembly, C and C++, I now work as a System Developer using a wide range of languages and technologies. However, my passion lies in creating excellent software using Go.

Updated on August 21, 2022

Comments

  • ANisus
    ANisus over 1 year

    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.

  • ANisus
    ANisus over 12 years
    I just tried that code as well. Unfortunately I still won't get the focus back. (I edited the question adding your suggestion)
  • ANisus
    ANisus over 12 years
    Clearly that was the trick! It works. That made my day! .. Now I only have a trailing new line from the event still lingering. But atleast I have my focus!
  • IDisposable
    IDisposable about 10 years
    What if you do that in a setTimeout to give the iframe a bit of time to start inflating?