Search code examples
applescriptautomator

Processing list of selected text in automator with applescript


While trying to make an automator action that opens multiple tabs from selected text as input I ran into an applescript issue I wasn't able to solve for awhile. This includes the answer and I'm posting this here because I just wasn't able to find documentation on how to handle data in "input" for a receives selected "text" in "any application" automator action, everything is for files which comes in as a list already.

When putting an applescript action in, you get:

on run {input, parameters}

the problem here is that input isn't in a list format and trying to do anything with it breaks the script or throws an error. ie I can't do:

        repeat with URL in input
        set this_URL to URL

So how can I treat a list of selected text as a list of items?


Solution

  • the solution is first treat input as a string then break apart every paragraph.

    on run {input, parameters}
    
    set inputText to input as string
    set URL_list to every paragraph of inputText
    

    Without treating input "as string" first before doing "every paragraph of" it won't work.

    Here's the end working script, replace the "some_url" with your own. You'll be able to select several lines of text in an editor and treat each one as a parameter to your fixed url opening each in a new safari tab. This could be expanded upon by having each line be delimited for multiple params on the url.

    on run {input, parameters}
    
    set inputText to input as string
    set URL_list to every paragraph of inputText
    tell application "Safari"
        activate
        repeat with URL in URL_list
            set this_URL to URL
            # extra processing of URL could be done here for multiple params
            my new_tab()
            set tab_URL to "http://some_url.com?data=" & this_URL
            set the URL of document 1 to tab_URL
        end repeat
    end tell
    return input
    end run
    
    on new_tab()
        tell application "Safari" to activate
        tell application "System Events"
            tell process "Safari"
                click menu item "New Tab" of ¬
                    menu "File" of menu bar 1
            end tell
        end tell
    end new_tab
    

    As an example say you had the list and had a service of the above using "http://stackoverflow.com/posts/" & this_URL

    6318162 
    6318163 
    6318164
    

    you could now select them click services and choose your "StackOverflow - view questions" service and it'll append and open each one in a new safari tab. In my case I needed to verify multiple dns entries in our server as still valid and do a bunch of whois lookups.