how to get selected text of any application into safari to google(AppleScript)

380 Views Asked by At

how to get selected text of any application into safari to google in AppleScript?

here is the sample code what am trying to do:

tell application "System Events" to set selectedText to get selection
     tell application "Safari"
         open location "https://www.google.com/search?q=" & selectedText
         activate
     end tell
end tell
1

There are 1 best solutions below

5
Robert Kniazidis On

In the past, I wrote the script for a similar task. You might also prefer this approach:

tell application "Safari"
    open location "https://www.google.com/search?q=" & selectedText
    activate
end tell

------------------------------- HANDLERS ------------------------------------

on getSelectedText(appName)
    
    tell application appName to activate -- bring application to front
    
    -- get selected text, if it is selected
    set the clipboard to "" 
    tell application "System Events" to keystroke "c" using command down
    set {aSelection, maxTimeOut} to {"", 0}
    repeat while aSelection is ""
        set maxTimeOut to maxTimeOut + 0.1
        if maxTimeOut > 1 then error "NOTHING SELECTED."
        set aSelection to (the clipboard) as text
    end repeat
    
    return aSelection

end getSelectedText

on encode_URL(txt)
    set python_script to ¬
        "import sys, urllib; print urllib.quote(sys.argv[1])"
    set python_script to "/usr/bin/python -c " & ¬
        quoted form of python_script & " " & ¬
        quoted form of txt
    return do shell script python_script
end encode_URL