Ask Different (Apple)
Q&A for power users of Apple hardware and software
Latest Questions
0
votes
1
answers
200
views
Batch modify metadata for local music files in the macOS Apple Music app using regex
I would like to batch modify metadata for local music files (mainly AAC in m4a, with some mp3) in my local music library from the macOS Apple Music app using regex. Specifically, I'd like to retitle tracks using matching groups from a regex on the existing title. Can this be done via any Apple scrip...
I would like to batch modify metadata for local music files (mainly AAC in m4a, with some mp3) in my local music library from the macOS Apple Music app using regex.
Specifically, I'd like to retitle tracks using matching groups from a regex on the existing title.
Can this be done via any Apple scripting facilities, like the Shortcuts app, the Automator app, or any other Apple-provided scripting?
In Shortcuts, I tried to pass the output from a "Find Music" action to a "Run JavaScript for Mac Automation" action, but I keep getting errors (like
The operation couldn’t be completed. (WFMacHelperErrorDomain error 1.)
even when I don't modify the run
function at all) no matter what I do.
If not, do any third-party scripting facilities work with the Apple Music API such that the files get modified through Apple Music, instead of directly modifying the files, then having Apple Music scan the file system for changes?
If nothing works with the Apple Music API, what third-party tools/libraries offer batch regex music metadata parsing & modification? For third-party scripting, I'd prefer JavaScript/zsh/Java/Kotlin/etc.
XDR
(664 rep)
Sep 4, 2024, 09:44 AM
• Last activity: Jun 29, 2025, 06:04 PM
1
votes
1
answers
278
views
Automator adding dots when I write code
When I type some code in the __Run JavaScript__ box in Automator, it’s always adding a few dots, sometimes replacing what I’m typing. This also happens with __Run AppleScript__, but not with __Run Shell Script__. I think it’s trying to second-guess what I’m typing, but I can’t work out what it’s thi...
When I type some code in the __Run JavaScript__ box in Automator, it’s always adding a few dots, sometimes replacing what I’m typing.
This also happens with __Run AppleScript__, but not with __Run Shell Script__. I think it’s trying to second-guess what I’m typing, but I can’t work out what it’s thinking.
Manngo
(3713 rep)
Sep 21, 2023, 11:00 PM
• Last activity: Jun 8, 2025, 12:02 AM
0
votes
1
answers
447
views
AppleScript : do JS on different Safari windows
I'm using some script which basically get text from safari, click button and fill up textfield. e.g : tell application "Safari" set texttograb to do JavaScript "document.getElementsByClassName('the_variable_as_text')[0].value;" in document 1 do JavaScript "document.getElementsByClassName('text-entry...
I'm using some script which basically get text from safari, click button and fill up textfield.
e.g :
tell application "Safari"
set texttograb to do JavaScript "document.getElementsByClassName('the_variable_as_text').value;" in document 1
do JavaScript "document.getElementsByClassName('text-entry').value=" & quoted form of myText in last tab of window 1
do JavaScript "document.getElementsByClassName('Approve-button').click();" in last tab of window 1
end tell
This work perfectly but I have a change in my workflow and I need to use different safari window.
How can I refer one javascript to one specific safari window and the other to a different window.
Especially when some tab might have the same URL/Name ?
I remember seeing that a while back (when the tab happen to have the same name but I never manage to run a script which refer to the window id
Otherwise I suppose I can use another web browser (e.g one safari the second safari technology preview) as a workaround but that not really ideal and limit to two windows
any idea how can I found the window ID and refer to it in AppleScript/JS ?
Kevin
(2468 rep)
May 29, 2020, 08:35 AM
• Last activity: Jun 5, 2025, 10:07 PM
1
votes
0
answers
418
views
Is there a method to have all links from a Chromium PWA application open in my default browser, Safari?
## Problem Statement On macOS, Is there a way to open all links from a Chromium PWA application in my default browser, Safari? Any advice or workarounds would be greatly appreciated. ## Scenario 1. Open Bing Chat Microsoft Edge's PWA application 2. Any link clicked to be opened in Safari application...
## Problem Statement
On macOS, Is there a way to open all links from a Chromium PWA application in my default browser, Safari? Any advice or workarounds would be greatly appreciated.
## Scenario
1. Open Bing Chat Microsoft Edge's PWA application
2. Any link clicked to be opened in Safari application instead of Microsoft Edge
## Attempted Solutions
I tried using **Choosy**, **Valjar**, and **Open In**. The only one that works but needs two clicks instead of one is **Choosy**, by right-clicking the link and pressing open in Choosy context menu. I thought of using Choosy API to prepend all links with Choosy using Tampermonkey user script. But I still cannot find a solid solution for my problem.
## Similar Threads/Posts
https://apple.stackexchange.com/questions/448871/mac-os-open-links-from-chrome-pwas-in-default-browser-instead-safari - No responses.
https://apple.stackexchange.com/questions/426786/how-to-open-https-links-which-are-part-of-a-webpage-in-firefox-or-chrome-in-th - Outdated, no-mention of chromium userscripts/tampermonkey with choosy API.
fatFeather
(158 rep)
Dec 18, 2023, 10:15 PM
• Last activity: Feb 13, 2025, 08:32 PM
2
votes
1
answers
83
views
Code works in ScriptEditor but not with osascript
I'm confused about what's going wrong here. I have this code ``` let Calendar = Application('Calendar'); console.log('Here #1'); console.log(Calendar.calendars.length); console.log('Here #2'); ``` If I run it in ScriptEditor the code works fine. I get this, expected, output. ``` /* Here #1 */ /* 17...
I'm confused about what's going wrong here.
I have this code
let Calendar = Application('Calendar');
console.log('Here #1');
console.log(Calendar.calendars.length);
console.log('Here #2');
If I run it in ScriptEditor the code works fine. I get this, expected, output.
/* Here #1 */
/* 17 */
/* Here #2 */
But if I run the code using osascript it doesn't give me the expected output.
(0)~/Documents>osascript -l JavaScript TestCalendar.scpt
Here #1
TestCalendar.scpt: execution error: Error: Error: An error occurred. (-1743)
System I am running on:
- MacBook Air
- Chip Apple M2
- MacOS Sequoia 15.1
user2004727
(23 rep)
Nov 4, 2024, 08:34 PM
• Last activity: Nov 8, 2024, 08:01 AM
1
votes
1
answers
95
views
Up to date documentation for Javascript for Automation (JXA)
Is there an up-to-date official documentation about Javascript for Automation (JXA)? I can find this, from 2015, [Introduction to JavaScript for Automation Release Notes](https://developer.apple.com/library/archive/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/Introd...
Is there an up-to-date official documentation about Javascript for Automation (JXA)?
I can find this, from 2015, [Introduction to JavaScript for Automation Release Notes](https://developer.apple.com/library/archive/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/Introduction.html#//apple_r) .
Is there anything newer?
Karel Bílek
(143 rep)
Apr 4, 2024, 09:29 AM
• Last activity: Jul 2, 2024, 05:34 PM
6
votes
1
answers
366
views
What are the JSDoc types of the parameters passed to run() in a JXA action?
When I add a `Run JavaScript for Automation` action to a Shortcut that I'm writing, it comes with a `run()` function: ```js function run(input, parameters) { // Your script goes here return input; } ``` https://apple.stackexchange.com/questions/270159/ has a number of responses with links that would...
When I add a
Run JavaScript for Automation
action to a Shortcut that I'm writing, it comes with a run()
function:
function run(input, parameters) {
// Your script goes here
return input;
}
https://apple.stackexchange.com/questions/270159/ has a number of responses with links that would be somewhat helpful if I were writing AppleScript, but so far, the best link, [The Structure of the on run
Command Handler](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/AutomatorConcepts/Articles/ImplementScriptAction.html#//apple_ref/doc/uid/TP40001512-97148-CJBIADBH) has only this to say about the contents of input
:
> The input
parameter contains (in most instances) the output of the previous action in the workflow; it is almost always in the form of a list.
This is less helpful than I'd hope for from first-party documentation.
So far, I've been able to figure this much out about what I can expect, describing it all using [JSDoc](https://jsdoc.app) types:
/**
* An item that is passed to an on-run handler.
*
* If you have plain text on the clipboard, this will be that as a string.
* If you have rich text on the clipboard, this will be a path to an RTF file in, roughly, /private/var/folders/…/com.apple.WorkflowKit.BackgroundShortcutRunner/Clipboard Written Out Date.rtf
.
* If you have one file on the clipboard, this will be its UNIX pathname.
* If you have multiple files on the clipboard, this will be a list-like object that will have all the path names.
* @typedef {string|object} InputItem
*/
/**
* A bundle of information passed in as the second (?) item in the array called input
.
* @typedef {string} InputInfo
* @property {string} [source] - the JavaScript source code of this action.
* @property {string} [temporary items path] - the path to a folder in /var/folders/…/com.apple.WorkflowKit.BackgroundShortcutRunner//com.apple.shortcuts.RunScript
* @property {boolean} ignoresInput - false if this action receives input, true otherwise.
*/
/**
* @param {[InputItem, InputInfo]} input
* @param {*} parameters
* @returns {InputItem | string}
*/
function run(input, parameters) {
// Your script goes here
return input;
}
I know that I can also return a string from the run
function, at least in some cases, because [it worked for me elsewhere](https://apple.stackexchange.com/a/430377/62570) .
Still, what kinds of object(s) can I expect in the input
and parameters
arguments?
I'm using the following to help me flesh out the different things that can get passed in:
function run(input, parameters) {
// Your script goes here
let ret = '';
for (const [k, v] of Object.entries(input)) {
ret += ---\nk: ${k}\nv: ${v}\nt: ${typeof v}\n
;
}
ret += '...\n'
const second = input;
if (second === undefined) return ret;
for (const [k, v] of Object.entries(second)) {
ret += ---\nk: ${k}\nv: ${v}\n
;
}
return ret;
}
adiabatic
(223 rep)
Nov 23, 2021, 06:18 AM
• Last activity: Jun 28, 2024, 12:45 PM
1
votes
1
answers
140
views
How to gracefully exit a JXA script on error?
I'm launching the myScript.js from terminal with: osascript -l 'JavaScript' myScript.js This is myScript.js: "use strict"; var app = Application.currentApplication(); app.includeStandardAdditions = true; var curlOutPath = "/Users/dev/curl_output.json"; try { const data = app.read(curlOutPath); const...
I'm launching the myScript.js from terminal with:
osascript -l 'JavaScript' myScript.js
This is myScript.js:
"use strict";
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var curlOutPath = "/Users/dev/curl_output.json";
try {
const data = app.read(curlOutPath);
const parsed = JSON.parse(data);
} catch(err) {
console.log(“1. Exit Here.”);
}
console.log(“2. This line should not execute.”);
I want to exit the script in the catch block. I've tried "return;", "exit;", "quit;" and they all don't work. I know JXA is poorly supported, so I thought I'd ask here to see if anyone knows the right keyword to use.
Dev
(19 rep)
Sep 7, 2023, 07:10 PM
• Last activity: Apr 1, 2024, 09:00 AM
3
votes
1
answers
157
views
Automator - Cyrillic symbols and file writing
I was quite surprised the fact that Apple Automator can make backups for my notes. So I wrote a small script for that. But there are two unsolved issues. 1. In for each files are creating but there are empty 2. The Cyrillic in files is writing like ????? 3. Is it possible somehow to get folder name...
I was quite surprised the fact that Apple Automator can make backups for my notes. So I wrote a small script for that. But there are two unsolved issues.
1. In for each files are creating but there are empty
2. The Cyrillic in files is writing like ?????
3. Is it possible somehow to get folder name to structure it with files like in Apple Note (Optional)
Could you please help me with this?
var app = Application.currentApplication()
app.includeStandardAdditions = true
function writeTextToFile(text, file, overwriteExistingContent) {
try {
var fileString = file.toString()
var openedFile = app.openForAccess(Path(fileString), { writePermission: true })
if (overwriteExistingContent) {
app.setEof(openedFile, { to: 0 })
}
app.write(text, { to: openedFile, startingAt: app.getEof(openedFile) })
app.closeAccess(openedFile)
return true
}
catch(error) {
try {
app.closeAccess(file)
}
catch(error) {
console.log(
Couldn't close file: ${error}
)
}
return false
}
}
var notesApp = Application('Notes');
notesApp.includeStandardAdditions = true;
var notes = notesApp.notes;
for(var i = 0; i < notes.length; i++) {
try {
var desktopString = app.pathTo("desktop").toString()
var file = ${desktopString}/copy/${notes[i].name()}.txt
var text = notes[i].body();
writeTextToFile(text, file, true)
}
catch(error) {
var desktopString = app.pathTo("desktop").toString()
var file = ${desktopString}/ERROR.log
writeTextToFile(error.message, file, true)
}
}
dsjfhdjshfjkdshjf
(31 rep)
Oct 5, 2022, 06:42 AM
• Last activity: Feb 29, 2024, 09:06 AM
0
votes
4
answers
1040
views
Use the Finder to act on a path, via JXA
For a specific example, here’s how to change the name of a specific file via the Finder, in AppleScript: tell application "Finder" to set name of (POSIX file "/some/file/path" as alias) to "new name" And here’s how to change the name of the *selected* file via the Finder, in JavaScript for Automatio...
For a specific example, here’s how to change the name of a specific file via the Finder, in AppleScript:
tell application "Finder" to set name of (POSIX file "/some/file/path" as alias) to "new name"
And here’s how to change the name of the *selected* file via the Finder, in JavaScript for Automation (JXA):
Application("Finder").selection().name = "new name"
How can one do the last line, but acting on a specific given path rather than being limited to the selection? It’s important to use the Finder, because it allows (via the same mechanism) to do more than change the name (like set a comment).
user137369
(1666 rep)
Dec 19, 2020, 03:33 AM
• Last activity: Jul 28, 2023, 05:52 PM
2
votes
0
answers
270
views
When using osascript (Javascript) how do I sent console.log messages to standard out
If I have this simple little comamnd ``` osascript -l JavaScript -e "console.log('hello')" > file.txt ``` I see the message on the terminal. However, it is not sent to file.txt. Any ideas on how to send osascript output to stdout?
If I have this simple little comamnd
osascript -l JavaScript -e "console.log('hello')" > file.txt
I see the message on the terminal. However, it is not sent to file.txt. Any ideas on how to send osascript output to stdout?
Scott Walter
(2383 rep)
Apr 24, 2023, 01:34 PM
1
votes
0
answers
192
views
Mac Automation / Scripting: create reminder item for each calendar event
I would like to automatically create a reminder item for each event in a particular calendar. Below is my automation script (JavaScript). `CALENDAR_NAME` is the source calendar name, `REMINDER_LIST_NAME` the target reminder list name. ``` // `osascript ./calender-to-reminder.js` const CALENDAR_NAME...
I would like to automatically create a reminder item for each event in a particular calendar. Below is my automation script (JavaScript).
CALENDAR_NAME
is the source calendar name, REMINDER_LIST_NAME
the target reminder list name.
// osascript ./calender-to-reminder.js
const CALENDAR_NAME = 'TODO';
const REMINDER_LIST_NAME = 'TODO';
const Calendar = Application('Calendar');
const Reminders = Application('Reminders');
const workCalendar = Calendar.calendars.byName(CALENDAR_NAME);
const calendarItems = workCalendar.events();
const reminderList = Reminders.lists.byName(REMINDER_LIST_NAME);
for (let i = 0; i r.name() === reminderName && r.dueDate() === reminderDueDate
);
if (existingReminders.length > 0) {
// Reminder already exists, update its note
const reminderToUpdate = existingReminders;
reminderToUpdate.body.set(reminderNote);
} else {
// Reminder doesn't exist, create a new one
const newReminder = Reminders.Reminder({
name: reminderName,
dueDate: reminderDueDate,
body: reminderNote
});
reminderList.reminders.push(newReminder);
}
}
While the script works, it's incredibly slow and only creates a few items **per hour**. During the entire time, the Reminder app is almost unresponsive. Since I'm trying to create a few hundred reminder items, the script would need days to complete. The source calendar is a subscribed calendar. I'm on macOS 13.2.1.
Does anybody know what the issue is and what I could change to make the script complete the work in a reasonable amount of time?
misc
(11 rep)
Mar 29, 2023, 08:13 AM
1
votes
0
answers
92
views
JXA (AppleScript) disabled other key on system.keystroke
I trigger CMD+C to get the content highlighted to the clipboard. My problem is that if the user does another key simultaneously, it breaks all the flow. Do you know any solution (like blocking other keys or something)? the code bellow ``` const system = Application('System Events'); system.keystroke...
I trigger CMD+C to get the content highlighted to the clipboard.
My problem is that if the user does another key simultaneously, it breaks all the flow.
Do you know any solution (like blocking other keys or something)?
the code bellow
```
const system = Application('System Events');
system.keystroke('c', {
using: ['command down'],
});
Castro Crea
(11 rep)
Mar 6, 2023, 11:00 AM
• Last activity: Mar 6, 2023, 12:47 PM
0
votes
0
answers
210
views
Compiled Javascript for Automation (JXA) script does not show applications
I wrote a small script to sync one folder to another as a Javascript for Automation script. If I run it directly from terminal: ```shell $ osascript -l JavaScript myscript.js ``` then it works as supposed - the referenced shell script is run, and then a dialog popup with the output of the shell scri...
I wrote a small script to sync one folder to another as a Javascript for Automation script.
If I run it directly from terminal:
$ osascript -l JavaScript myscript.js
then it works as supposed - the referenced shell script is run, and then a dialog popup with the output of the shell script is shown, and then the notification is shown in the top right corner.
Now, I need this script to have full disk access to run it via launchd
. For that, I compile the script into an application:
osacompile -l JavaScript -o myapp.app myscript.js
Now, if I run the resultant app:
open myapp.app
everything works (the app requests access to external volume, as should be), but unfortunately, the notification is not shown in the top right corner. It seems like macOS does not register the app for shown notifications (it does not appear in the notifications pane in System preferences).
How can I solve this bug with notifications? Thank you!
The myscript.js
content:
```js
const app = Application.currentApplication();
app.includeStandardAdditions = true;
console.log("Start sync-archive");
const home = app.systemAttribute("HOME");
const script = home + "/.launchd/sync-archive/sync-archive.sh";
const res = app.doShellScript("zsh " + script);
app.displayDialog(res);
if (res.includes("success")) {
app.displayNotification("completed successfully", {
withTitle: "sync-archive",
});
console.log("Finish sync-archive: success");
} else {
app.displayAlert("sync-archive failed", {
message: "Please see " + script + " and logfiles",
as: "warning",
});
console.log("Finish sync-archive: failure");
}
Dmitry Kabanov
(163 rep)
Dec 6, 2022, 07:41 PM
3
votes
1
answers
371
views
In Finder, how dynamically change folder icon's color when said folder contains .git folder?
Looking for an automated way, in macOS Finder, to change a folder icon from its default blue to green, based on whether or not it contains a `.git` repository. Can this be scripted or automated with a finder extension or some other tool?
Looking for an automated way, in macOS Finder, to change a folder icon from its default blue to green, based on whether or not it contains a
.git
repository.
Can this be scripted or automated with a finder extension or some other tool?
user451908
Feb 28, 2022, 09:56 AM
• Last activity: Apr 1, 2022, 09:01 PM
2
votes
2
answers
763
views
What is the javascript equivalent of the applescript run command?
I want to create a script for opening an app in nonstandard location quickly. With AppleScript, the app can be started with: ``` tell application [app path] to run ``` I want to do the same using javascript cause I am more familiar. But `Application([app path]).run()` does not work. In fact, the App...
I want to create a script for opening an app in nonstandard location quickly. With AppleScript, the app can be started with:
tell application [app path] to run
I want to do the same using javascript cause I am more familiar. But Application([app path]).run()
does not work. In fact, the Application object does not seem to have any attributes.
cdowen
(519 rep)
Dec 23, 2021, 09:58 AM
• Last activity: Dec 24, 2021, 02:07 AM
0
votes
0
answers
136
views
Adobe Bridge Javascript works on Windows but not Mac
I have a bridge script here that I have been running on Adobe Bridge 2022 for Windows but when I tried to run it on an imac it did not work. I have never had issues with using photoshop scripts on both machines, but this bridge one doesn't seem to take? --- function re() { rplcd = fle.path + '/' + d...
I have a bridge script here that I have been running on Adobe Bridge 2022 for Windows but when I tried to run it on an imac it did not work. I have never had issues with using photoshop scripts on both machines, but this bridge one doesn't seem to take?
---
function re() {
rplcd = fle.path + '/' + decodeURI(fle.name)
.replace(/ .+(?=\.jpg)/, '_' + bdefgh.shift())
return File(rplcd).name != nme && rplcd
}
rnmng = new MenuElement('command', 'Batch Renaming',
'at the end of Thumbnail'), rnmng.onSelect = function() {
fls = File(pP = app.document.presentationPath).getFiles(/\.jpg$/i), cde = ''
while(fls.length) ((slc = (nme = (fle = fls.shift()).name).slice(0, 17)) != cde) &&
(cde = slc, bdefgh = 'bdefgh'.split('')), (rslt = re()) && fle.rename(rslt)
}
Ron Ibarra
(1 rep)
Dec 6, 2021, 01:12 PM
• Last activity: Dec 6, 2021, 01:55 PM
2
votes
1
answers
3392
views
Shortcut to login to website using JavaScript
Trying to make a shortcut on Apple iPhone to login to website using JavaScript in the shortcut. The html of the login page is: User ID Web Login Password Sign In Unable to trigger click or find submit button with only a “.title” not “.Id” The following is the JavaScript I’m using in the shortcut: va...
Trying to make a shortcut on Apple iPhone to login to website using JavaScript in the shortcut.
The html of the login page is:
Unable to trigger click or find submit button with only a “.title” not “.Id”
The following is the JavaScript I’m using in the shortcut:
var result = [];
var emailTextBox = document.getElementById("username");
emailTextBox.value = "myUserName";
var pwTextBox = document.getElementById("password");
pwTextBox.value = "myPassword";
var submitBtn = document.getElementById("Sign In").title;
submitBtn.click();
// Call completion to finish
completion(result);
User ID
Web Login Password
Sign In
BarclayVision
(123 rep)
Jun 10, 2021, 05:43 PM
• Last activity: Jun 10, 2021, 07:13 PM
0
votes
1
answers
231
views
How to execute pre-defined JavaScript function in AppleScript and pass data to JavaScript
In my AppleScript, I want to pass a list of keys to a website's client-side, then query the data on the backend, and get the response and re-render the client-side. All of these should happen in the background so that the user won't notice it. Previously, I was able to create a dummy button (set it...
In my AppleScript, I want to pass a list of keys to a website's client-side, then query the data on the backend, and get the response and re-render the client-side. All of these should happen in the background so that the user won't notice it.
Previously, I was able to create a dummy button (set it as a hidden button), and click the button in AppleSciprt, then trigger the onClick event in my website:
tell tab t to set RemoveBtRestriction to execute javascript "document.getElementById('myButton').click()"
But now my requirement is to pass data to the client, how to achieve this? Is it possible to execute a JavaScript function like this directly, which the loadKeys function is pre-defined my client-side:
set keys = 'key1,key2,key3';
tell tab t to execute javascript "loadKeys(keys)"
Any ideas would be appreciated, thanks in advance!
123mig
(1 rep)
Dec 17, 2020, 03:12 AM
• Last activity: May 16, 2021, 04:03 PM
1
votes
0
answers
382
views
How can I edit and run Apple Script with an editor other than Script Editor?
I've recently been writing more AppleScript, now that Apple has added Javascript support. But how can I edit and run Javascript Automation code in an editor other than the built-in Script Editor? My ideal editor would be TextMate, but anything that has good syntax highlighting and automatic indentin...
I've recently been writing more AppleScript, now that Apple has added Javascript support.
But how can I edit and run Javascript Automation code in an editor other than the built-in Script Editor? My ideal editor would be TextMate, but anything that has good syntax highlighting and automatic indenting would be good enough for me.
Bill
(442 rep)
Mar 13, 2021, 01:58 PM
Showing page 1 of 20 total questions