Search code examples
applescriptjavascript-automation

How to mount a volume and open a folder with Apple JXA


I'd like to mount a volume and then immediately open a Finder window to a specific path but I'm having trouble converting from Apple Script to JXA.

I want the JXA equivalent of something like this:

tell application "Finder"
    if not (disk "Airport Time Capsule" exists) then
        mount volume "afp://AirPort%20Time%20Capsule._afpovertcp._tcp.local"
    end if
    open "/Volumes/Airport Time Capsule"
end tell

I've tried a few things but nothing seems to work. Complete documentation for JXA is non-existent.

var finder = Application('Finder');
finder.mount('afp://.....'); // doesn't work
finder.mount.volume('afp://.....'); // doesn't work
finder.mountVolume('afp://.....'); // doesn't work

Solution

  • The following code should roughly emulate your AppleScript. It checks if a disk with the specified name ("AirPort Time Capsule") is already mounted, opens such a disk if one is, or else connects to the Time Capsule using the openLocation function (which requires standardAdditions):

    var finder = Application('Finder')
    finder.includeStandardAdditions = true
    var disks = finder.disks.where({name: 'AirPort Time Capsule'})
    if (disks.length > 0) {
        finder.open(disk[0])
    } else {
        finder.openLocation('afp://[your-time-capsule].local')
    }
    

    I actually had to change "AirPort Time Capsule" to "MobileBackups" on my laptop, so you might try that if the above code doesn't work.