MacOS – change url of a tab using apple script

applescriptgoogle-chromemacos

I am trying to set the url of Chrome tab using Apple Script. I am using this code. It successfully sets url string, but in order to change url, enter needs to be pressed. This last step makes my code unfunctional, since it doesn't change the current website I am visiting. What workaround do you recommend? Chrome is already open.

tell application "Google Chrome"

    tell application "System Events"
        tell application process "Google Chrome"
            set value of text field 1 of toolbar 1 of window 1 to "http://www.url.com/"

        end tell
    end tell
end tell

Best Answer

A way to do it with Chrome's built in scripting:

tell application "Google Chrome" to set URL of active tab of window 1 to "http://example.com"

And to expand your script to press return:

tell application "Google Chrome"
    tell application "System Events"
        tell application process "Google Chrome"
            set (text field 1 of toolbar 1 of window 1)'s focused to true
            set value of text field 1 of toolbar 1 of window 1 to "http://example.com/"
            keystroke return
        end tell
    end tell
end tell