The Bomb Squad
The Bomb Squad

Reputation: 4337

How to put your cursor in the input tab

in Google, I put the code document.querySelector('[aria-label="Search"]').select(); How to put your cursor in the input tab in console log to see if the input tab of google gets selected. I confirmed that I correctly called the input tab but the console log just said undefined How to put your cursor in the input tab with javascript. If it can't be javascript, please still share how to put your cursor in the input tab

Upvotes: 1

Views: 151

Answers (1)

Ryan Pendleton
Ryan Pendleton

Reputation: 2626

The code you have is correct. There are really two parts to your question:

Why does the console show undefined after running .select()?

To make sense of the undefined, it's important to understand how the console works. When you enter an expression in the console, it runs it using eval and displays the result. For example:

  • 1 + 3 evaluates to 4
  • var a = 1 + 3 evaluates to undefined, even though a variable was defined
  • alert("hello") evaluates to undefined, even though an alert was displayed

In your example, HTMLInputElement.select() doesn't return anything, so the console simply displays undefined. With that being said, the code did in fact run. You can verify this by displaying an alert using the console.

(If you're interested in the specifics of how the console decides what to display as the result of an expression, I'd take a look at this answer.)

Why doesn't the search field focus when running .select() using the console?

For this part of your question, I'd recommend experimenting with the source of a page you control. Notice that if you setup a button to call .select() on a text field, the field will focus. If you run that same code using the console, the field won't focus.

While I'm not sure of the specifics, it seems this is because the developer tools refuse to lose focus without the user specifically clicking a different element or closing them. If you instead wrap your expression in a timeout and change your focus before the timeout executes, your code works as expected.

You can verify this on both your page and Google's by doing the following:

  1. Use the console to run:

    setTimeout(() => document.querySelector('[aria-label="Search"]').select(), 2000)
    
  2. Quickly click the background of the page to resign focus of the developer tools.

  3. Observe that the field focuses when the timeout executes.

Upvotes: 1

Related Questions