Search code examples
applescript

Is there a way to make a custom library in AppleScript?


So I have a set of functions that I call in almost every script I write. Is there a way to store them that I can call them without pasting 100 lines of code in every project?


Solution

  • For in depth details, have a look at Creating a Library in the AppleScript Language Guide.

    As a quick example, in macOS Catalina, I created the Script Libraries folder in the Library folder of my Home folder, in Terminal:

    mkdir -p "$HOME/Library/Script Libraries"
    

    In Script Editor, I saved a script named My Library.scpt in the Script Libraries folders in the Library folder of my Home folder, containing a handler I use often with Safari:

    Example AppleScript code:

    to waitForSafariPageToFinishLoading()
        --  # Wait for page to finish loading in Safari.
        --  # This works in **macOS Catalina** and 
        --  # macOS Big Sur and may need adjusting for
        --  # other versions of macOS.
        tell application "System Events" to repeat until ¬
            exists (buttons of groups of toolbar 1 of window 1 of ¬
                process "Safari" whose name = "Reload this page")
            delay 0.5
        end repeat
    end waitForSafariPageToFinishLoading
    

    I then used the waitForSafariPageToFinishLoading() handler in another script in this manner:

    Example AppleScript code:

    property myLibrary : script "My Library"
    
    property theURL : "https://stackoverflow.com/questions/68581982/" & ¬
        "is-there-a-way-to-make-a-custom-library-in-applescript"
    
    tell application "Safari" to ¬
        make new document with properties {URL:theURL}
    
    myLibrary's waitForSafariPageToFinishLoading()
    
    display alert "The web page has finished loading!"
    

    In the example AppleScript code, shown directly above, Safari waits for the web page to finish loading, using a handler from My Library.scpt, and then displays an alert message.



    Note: Libraries are supported in OS X Mavericks v10.9 (AppleScript 2.3) and later. To share properties and handlers between scripts in prior OS versions, use the load script command as described in Libraries using Load Script.

    Note that the load script method can still be used with newer versions of the OS.

    Update:

    Also note that the question asked was about "Is there a way to make a custom library in AppleScript?", not how to use them and why I said "As a quick example". However, that said, for practical long term usage, to the point mentioned in the other answer, I'd use e.g.:

    set myLibrary to ¬
        load script alias ¬
            ((path to library folder from user domain as text) & ¬
                "Script Libraries:My Library.scpt")
    

    Instead of:

    property myLibrary : script "My Library"