How to make Automator service that enters highlighted text into Chrome address bar?

I'm trying to make an Automator Quick Action that will show up in the right click menu under Services that will take the highlighted text and put it in a new tab in Chrome.

Looking at various other posts, I attempted this AppleScript, but it doesn't work:

on run {input, parameters}
tell application "Google Chrome"
    set myTab to make new tab at end of tabs of window 1
    tell application "System Events"
        tell application process "Google Chrome"
            set value to input
            keystroke return
        end tell
    end tell
end tell
end run

I can get it to work for a URL, but I want this to work for non-URLs too (and just perform the default Chrome behavior with that text).


Solution 1:

Update:

On the day this answer was originally posted, this worked with the then current version of Google Chrome.

As is typical with software updates they break code that worked in previous versions.

As of the date of this update and testing with the latest release of Google Chrome Version 90.0.4430.93 (Official Build) (x86_64), you need to add a toolbar 1 of ¬ in between the two group 1 of ¬ to update the code to work with this latest release of Google Chrome.



Original Answer

Not sure why you need this when you can select text, then right-click and select Search Google for “$selected_text” which essentially does the same thing as you're trying to do with a Quick Action service.

The following example AppleScript code does what you're looking to do:

on run {input, parameters}
    tell application "Google Chrome"
        activate
        if (count window) is equal to 0 then make new window
        make new tab at end of tabs of window 1
    end tell
    delay 0.5
    tell application "System Events"
        set value of ¬
            text field 1 of ¬
            group 1 of ¬
            group 1 of ¬
            window 1 of ¬
            application process "Google Chrome" to ¬
            input as text
        key code 36
    end tell
end run

Note that in order for this Quick Action service to work, Google Chrome and any other application you trigger the service from needs to be added to: System Preferences > Security & Privacy > Privacy > Accessibility

Additionally, Google Chrome needs to allow System Events under: System Preferences > Security & Privacy > Privacy > Automation

Automator Quick Action


Note: The example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay command may be necessary between events where appropriate, e.g. delay 0.5, with the value of the delay set appropriately.