JXA: How to use openForAccess

Published on by Geoff Taylor

Apple’s documentation shows that to open a file for writing in a JXA script, you call the openForAccess method on an Application instance. What the documentation doesn’t make clear is that you must call openForAccess on the instance returned by Application.currentApplication(). Anything else will fail.

If you run this code in Script Editor…

let app = Application('Finder');
app.includeStandardAdditions = true;
let desktop = app.pathTo('desktop').toString();
let myFile = `${desktop}/temp.txt`;
let openedFile = app.openForAccess(Path(myFile), { writePermission: true });
app.closeAccess(openedFile);

… it produces an privilege violation error.

  Script Editor error message

Script Editor even helpfully tells you that the privilege violation occurred on the line where we attempted to open the file.

But if you change Application('Finder') to Application.currentApplication(), it works.

let app = Application.currentApplication();
app.includeStandardAdditions = true;
let desktop = app.pathTo('desktop').toString();
let myFile = `${desktop}/temp.txt`;
let openedFile = app.openForAccess(Path(myFile), { writePermission: true });
app.closeAccess(openedFile);
  Script Editor no error message

(“Undefined” simply means the last statement didn’t return a value.)

If you need to open a file for writing, you must set a variable to Application.currentApplication() and call openForAccess on that Application instance — even if you’re already working with another application.

JXA: Find My Purchased Music

Published on by Geoff Taylor

I was looking at one of my playlists and wanted to know which songs I owned and which were from Apple Music, so I wrote a JXA (JavaScript for Automation) script. It works in macOS Catalina (10.15) and Mojave (10.14). Learn more and download the script from the GitHub repository.

Last Light

Published on by Geoff Taylor

Sunset and trees

Last light

Jan 7, 2020 18:18

Jan 7, 2020 18:18

Southwest Georgia pines and sky

Published on by Geoff Taylor

Southwest Georgia pines and sky

Southwest Georgia pines and sky

Dec 25, 2019 10:42

Dec 25, 2019 10:42

Fallen trees, one year after Hurricane Michael

Published on by Geoff Taylor

Fallen trees

Fallen trees, one year after Hurricane Michael

Dec 25, 2019 16:30

Iron City, Georgia

Dec 25, 2019 16:30Iron City, Georgia