Set focus on iframes in Chrome

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

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

How to adjust focus so that I can continue to enter text in an 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 have tried many solutions on other issues, but nobody is working.

+4
source share
4 answers

The trick is to set focus on the body first, 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); 
+2
source

This question has been answered here.

Basically, if you are not updating the iframe, you can use:

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

Note that I grab the underlying DOM iframe object.

+2
source

I tried below solution that works in all browsers (IE / Chrome / Firefox)

Context: I want to constantly focus the iframe.

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

Hope this helps if someone needs ...

+1
source

I tested this solution using Chrome. I originally placed it in the focus setting on the contents of the iframe .

Here is the code to create an iframe using jQuery, add it to the document, poll it before loading it, and then concentrate it. This is better than setting an arbitrary timeout, which may or may not work depending on how long it takes to load the iframe.

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

The iframe boot detection code was adapted from Biranchi to answer How to check if if iframe is loaded or has content?

0
source

Source: https://habr.com/ru/post/1380988/


All Articles