Search code examples
macosterminalapplescripturl-scheme

Run a Terminal command on open location AppleScript


I want to run a command in terminal when a custom url is called.

Example :

I want to open a terminal and run echo "hello myapp://hello" when someone opens myapp://hello in browser or when some one executes open "myapp://hello"

I am new to apple script so I searched a lot but was unable to conclude with a working code snippet.

I tried :

on open location this_URL
    display alert this_URL
    tell application "Terminal"
        reopen
        do script "echo 'hello " & this_URL & "'"
        activate
    end tell
end open location

Updated the Info.plist as:

.....
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLName</key>
    <string>myapp</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>myapp</string>
    </array>
  </dict>
</array>
....

This code just opens a terminal but doesn't runs the echo command. Standalone parts of code :

on open location this_URL
    display alert this_URL
end open location

and

tell application "Terminal"
    reopen
    do script "echo 'hello " & this_URL & "'"
    activate
end tell

Works perfectly.

But the combination doesn't work....

Please tell me some workaround.

Thanks in advance


Solution

  • I think this is problem with authorization.

    I don't know why but when we add CFBundleURLTypes in plist then macOS prevents us to send events to terminal.

    So here is a workaround :

    Make 2 apps instead of one as follows

    App 1 : url handler

    So this will handle the incoming url copy it to clipboard and initiate the 2nd app. Its applescript will be as follows :

    on open location this_URL
        set the clipboard to this_URL
        tell application "/path/to/app2.app" to activate
    end open location
    

    Add CFBundleURLTypes to its plist

    App 2 : Terminal handler

    It will read the url from clipboard and then run it on terminal. Its applescript will be as follows :

    tell application "Terminal"
        set this_URL to ( the clipboard as text )
        do script "echo 'hello " & this_URL & "'"
        activate
    end tell
    set the clipboard to ""