javascriptjquerygoogle-chromegoogle-chrome-extensionomnibox

Highlight the URL/omnibox text on new tab load (Chrome)


How do I programatically select the URL text once the new tab has loaded?

This is the code for redirect.js

/*global chrome,document,window */
(function init() {
    "use strict";
    chrome.storage.local.get(["url","tab.selected"], function (items) {
        var url = items.url;
        if(url) {
            var selected = items["tab.selected"] === undefined ? true : (items["tab.selected"] == "true");
            chrome.tabs.update({
                "url": url,
                "selected": selected
            });
        } else {
            angular.resumeBootstrap();
        }
    });
}());

Soon as the page at "url" is loaded, I want it to automatically highlight the URL/omnibox text so the user can start typing without pressing Ctrl+A.

Thank you

EDIT: The focus is on the omnibox, but the text already present is not highlighted. I want it so that it is highlighted.


Solution

  • I was able to solve this using a Workaround.

    Using Autohotkey, I coded a simple script which:

    1. monitors for new windows.
    2. When a new window is detected, it checks the name of the window to see if it is "chrome://..." (I add the '...' because using users can choose what to display on the new tab page. I have chrome://apps/ as my new tab page.
    3. Upon discovering the new window was chrome://..., it sends the Ctrl+A keystroke which selects the entire text in the omnibox.

    Simple. Elegant :P

    Here is the code, modify as you wish (you will need Autohotkey_L to execute the code. Alternatively, you can turn it into an .exe for compatibility. See documentation on link above.

    #Persistent
    #SingleInstance, Force
    #NoTrayIcon
    SetBatchLines, -1
    SetTitleMatchMode, 2
    SetWinDelay, -1
    
    /** Enter the name of the Chrome new tab page here, for me it is "Apps - Google Chrome" */
    
    ChromeTab := "Apps - Google Chrome"
    
    Gui +LastFound
    hWnd := WinExist()
    
    DllCall( "RegisterShellHookWindow", UInt,hWnd )
    MsgNum := DllCall( "RegisterWindowMessage", Str,"SHELLHOOK" )
    OnMessage( MsgNum, "ShellMessage" )
    Return
    
    ShellMessage( wParam,lParam ) {
        Global Last
        if (wParam = 16 && Last = 6) {
            WinGetActiveTitle, T
            if (T = ChromeTab) {
                SendInput, {Control Down}l{Control Up}
            }
        }
        Last := wParam
    }