Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to steal focus from the omnibox in a Chrome extension on the new tab page?

I'm making a Chrome extension that involves putting a text input on the new tab page, and immediately giving focus to that input text when the new tab page loads. After being unable to get focus using traditional methods (e.g. focus()), I stumbled upon this question:

Chrome 27: New Tab Page extension can't steal focus from Omnibox

which states that Chrome has now made it so that you can't steal omnibox focus on a new tab page. Given that Chrome is fine with giving focus to any site that isn't the new tab page, I've been trying to come up with workarounds, but nothing is really satisfactory.

I've tried:

  • Having the new tab page redirect immediately to locally-stored HTML file, but this still doesn't give focus because the page never had focus while redirecting.

  • Overriding ctrl+t and cmd+t in a content script to open up a new tab with the contents of a locally-stored HTML file. This works fine, except it seems you can't override cmd+t, so Mac users would be forced to use ctrl+t. Also, some sites (e.g. OneNote online editor) take over ctrl+t, so it doesn't work on every page.

  • Hosting the page remotely and having the new tab page redirect to it (far too slow).

  • Suggesting users press tab twice to focus on the input text when opening a new tab :)

Does anyone have any other suggestions as to how you might work around this restriction? It's pretty critical to my extension.

Thanks!

like image 644
Greyson Parrelli Avatar asked Jul 11 '13 16:07

Greyson Parrelli


People also ask

How do I focus a tab in Chrome?

Focus Mode in Chrome Make sure you run Google Chrome Canary and that the browser is up to date. Load chrome://flags/#focus-mode. Set the flag to Enabled. Restart Google Chrome.

Where is the Omnibar in Chrome?

The bar at the top of Chrome is called the omnibox (or Omnibar). It combines your regular address bar and the Google search box into one area in your browser. It's a powerful tool that can be used in a variety of ways.


1 Answers

Hello from my question you linked!

On your New Tab Page, include the following JavaScript:

chrome.tabs.create({ url: chrome.extension.getURL("foo.html") });
window.close();

This will create a "normal" tab, and then close the New Tab Page. You can then focus() your input box on the normal tab.

This is what I've done for my Fauxbar extension. It adds a slight delay when clicking Chrome's New Tab button (in terms of how long it takes for your input box to become focused), but I reckon it's better than having to press Tab.

You could also implement chrome.commands to create keyboard shortcuts that users can modify themselves under chrome://extensions > Keyboard shortcuts.

like image 121
Chris McFarland Avatar answered Nov 05 '22 22:11

Chris McFarland