Event focus () does not work through the browsers console

6

When I try to test something over the web, I end up using the console of the% s ( F12> Console ) to check for some behavior, especially for . However, I recently noticed that the event .focus () does not work as expected .

See the example below:

<input id="teste" type="text" id="teste" />

<br/><br/><br/>

<button onclick="document.getElementById('teste').focus()">teste</button>

If I click the "test" button, the browser will have focus, but if I type the same command that is in input in onclick() , nothing happens. >

Given this, how do console work and why it happens?

  

Note: This is not only because of the snippet. If I try to do the same with the .focus() search of the SOpt, nothing happens:

     

input

    
asked by anonymous 18.10.2017 / 03:33

2 answers

5

I think it's something related to "behavioral politics" , the same thing happens in Firefox as well as Chrome.

When you are in DevTools (Chrome or Firefox console), the browser tab or window is not in focus and then any <input> or <textarea> will not receive focus , a simple test is to add a timeout to the Console, inside the SOpt site itself open the console of your browser and enter this:

setTimeout(function () {
    document.querySelector('.top-bar .searchbar input[type="text"].f-input').focus();
}, 5000);

You will have 5 seconds to go back to the tab, then click anywhere on the site other than link, input or textarea and as soon as the 5 seconds pass the input will receive focus.

Now do another test, but instead of letting the tab in focus and type with setTimeout with 5 seconds again, wait 6 seconds, leave the tab in focus, click on the tab and not on the page, you will notice that it will receive the focus too, ie "inputables" elements only get focus when the flap or page is in focus.

See an example without timeout , if I click on the tab to focus on it, but not on the body of the page, the input will already be "marked / signaled" to receive the focus when the flap is also in focus:

    
18.10.2017 / 03:49
4

Because this is the way the browser works on the console (so much that it ignores and returns undefined ).

Whenever you run a command on the console, focus will always be on the command line, waiting for the next command, ignoring any focus points for some element on the page.

However, if you run the command below and immediately click anywhere on the page, the focus will work:

setTimeout(function(){document.getElementById('teste').focus()},5000);

Why?

Because you took focus from the console and the command will run normally after 5 seconds.

Test here on SOpt:

Run the command below in the console (F12) and immediately click on any area of the page (blank area, empty) or close the console:

setTimeout(function(){document.querySelector('#search > input').focus();}, 5000);
    
18.10.2017 / 03:50