Chris
Chris

Reputation: 14218

element.focus() with open developer console not working

I want to programmatically focus on an input:

document.getElementById('widgetu25071_input').focus()

This does not work when the developer console is open. Is there some way to do it without closing the console first?

You can recreate the issue on google.com:

Open console and execute:

document.getElementById('lst-ib').focus();

result for me: does not focus

now try: open console and execute:

setTimeout(function() {
document.getElementById('lst-ib').focus();
}, 9000);

close console quickly. Focus works when the timeout is finished.

Upvotes: 9

Views: 2307

Answers (1)

Brad
Brad

Reputation: 840

I forget about this every couple years and it drives me crazy until I remember again. So I'm adding an answer for myself and anyone else...

JavaScript basically thinks you're in a different application and can't steal focus to focus wherever you want to focus. ; ) You'll find this behavior if your cursor is in the console or in the URL bar of the browser.

Mouse hover events will still fire but you won't be able to gain focus anywhere on the page unless focus is already on the actual page.

So for example, if you have a little popup that contains a text field and it shows on mouse hover of some other element, you'll get the pop-up on mouse hover but you won't get that text field to focus if your cursor is in the console or in the URL bar.

As a crazy guess I'd say without this, a bad programmer could keep you from navigating away from the page (or doing anything else) by stealing focus back to the page every time you click in the URL bar or the console.

I hope this helps someone even if It's five years later.

Upvotes: 7

Related Questions