AppleScript

RSS for tag

AppleScript allows users to directly control scriptable Macintosh applications as well as parts of macOS itself.

Posts under AppleScript tag

42 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

How to access comments and their associated text in iWork documents via AppleScript/ScriptingBridge?
Hi all, I’m developing a Mac OS application with XCode that interacts with iWork documents (Pages, Numbers, Keynote) using ScriptingBridge (and maybe AppleScript). Right now I started with Pages, assuming if it works for Pages, it will likely be similar for Numbers and Keynote. While I can successfully access and modify the main body text (e.g. the “body text” property in a Pages document), I’m having major difficulties accessing the comments (or annotations) within these documents. There are many aspects, but right now what I’m trying to achieve: For a Pages document, I need to scan the document and extract, for each comment: The content of the comment (i.e. the comment’s text). The text that is being commented on. For Numbers, similarly, I need to retrieve the commented cell’s content and the associated comment. For Keynote, the same as Pages, except I manage to get the Presenter Notes. Once done, I could replace the content accordingly. What I’ve tried: Using AppleScript commands such as: every comment of document "Test" Accessing properties like content or range of a comment. Attempting various syntaxes (including using class specifiers) to force AppleScript to recognize comments. Using ScriptingBridge in my Swift code, but I couldn’t find any mapping for a “comment” object in the Pages dictionary. However, all these attempts result in errors such as “cannot convert …” or “this class is not key value coding-compliant for the key …” which leads me to believe that the iWork scripting dictionaries may not expose comments (or annotations) in a scriptable way. Questions: Is there a supported way to access the comments (and the associated commented text) in an iWork document via AppleScript or ScriptingBridge? If so, what is the proper syntax or property name to use? (For example, should I be looking for a class named “comment”, “annotation”, or perhaps something else?) If direct access via AppleScript/ScriptingBridge is not possible, what alternative approaches would you recommend for programmatically extracting comment data from iWork documents? I apologize if my post isn't clear, it is translated from French. Any insights or examples would be greatly appreciated. Thank you!
0
0
82
1d
Automator error when running Watch Me Do-created script
Hi everyone, I'm trying to use Automator to batch process PDF files. I have hundreds of academic journal article PDFs whose page sizes vary from 5x7 inches to A4 format (8.27 x 11.69 inches). I want to scale all the PDFs to US Letter size (8.5 x 11.0 inches) such that smaller originals remain 100% scale but are centered on the larger page and larger originals are scaled down to fit the page. Manually opening a PDF in Preview.app, scaling it to US Letter paper, and using the Save as PDF option is producing the desired output for me. I captured my workflow using the Watch Me Do action in Automator, then adjusted it into the following AppleScript. -- a Get Specified Finder Items action to specify the input PDFs precedes this script on run {input, parameters} repeat with filePath in input -- Open the file in Preview tell application "Preview" open filePath activate end tell -- Give Preview some time to open the file delay 2.0 -- Press ⌘P set timeoutSeconds to 0.25 set uiScript to "keystroke \"p\" using command down" my doWithTimeout(uiScript, timeoutSeconds) -- Click the “Scale to Fit:” radio button. delay 2.0 set timeoutSeconds to 2.0 set uiScript to "click radio button \"Scale to Fit:\" of radio group 1 of group 1 of group 2 of scroll area 2 of splitter group 1 of sheet 1 of window 1 of application process \"Preview\"" my doWithTimeout(uiScript, timeoutSeconds) -- Click the “<fill in title>” menu button. delay 4.0 set timeoutSeconds to 2.000000 set uiScript to "click menu button 1 of group 2 of splitter group 1 of sheet 1 of window 1 of application process \"Preview\"" my doWithTimeout( uiScript, timeoutSeconds ) -- Save as PDF… delay 2.0 set timeoutSeconds to 2.0 set uiScript to "click menu item 2 of menu 1 of splitter group 1 of sheet 1 of window 1 of application process \"Preview\"" my doWithTimeout(uiScript, timeoutSeconds) -- Click the “Save” button. delay 8.0 set timeoutSeconds to 2.0 set uiScript to "click UI Element \"Save\" of sheet 1 of sheet 1 of window 1 of application process \"Preview\"" my doWithTimeout(uiScript, timeoutSeconds) -- Press ⌘W to close the file delay 0.25 set timeoutSeconds to 2.0 set uiScript to "keystroke \"w\" using command down" my doWithTimeout(uiScript, timeoutSeconds) end repeat return input end run on doWithTimeout(uiScript, timeoutSeconds) set endDate to (current date) + timeoutSeconds repeat try run script "tell application \"System Events\" " & uiScript & " end tell" exit repeat on error errorMessage if ((current date) > endDate) then error "Can not " & uiScript end if end try end repeat end doWithTimeout My problem arises at the Save as PDF step. When this action runs, I see the PDF menu pop open: but the Save as PDF... menu item doesn't get clicked. Instead, I get an error: Can anyone advise on how to overcome this error?
1
0
159
5d
"Not authorized to send Apple events to Terminal
We are trying to open an application "xyz.app" It worked fine until 15.1.1 versions. But facing issues with 15.2 and 15.3 The application is working fine when we navigate to xyz.app/Contents/MacOS/ and run applet in this directory. But the error "Not authorized to send Apple events to Terminal" occurs when we are trying to open the app directly. We have tried with all the available solutions like giving full disk access to terminal and application, adding my application to automation in privacy and security tabs in settings. Any help would be appreciated. Thanks!
1
0
151
1w
Check to make sure iTunes is playing - AppleEvent timed out. (-1712)
Hi folks, I've got some music that I want playing on iTunes all the time on an older system, but it'll sometimes stop. I tried making a Applescript to check and play the music/playlist again if it stops, but I keep getting a timeout error. This is the AppleScript: repeat tell application "iTunes" if player state is paused then tell application "iTunes" to play end if delay 30 end tell end repeat I get this error: AppleEvent timed out. iTunes got an error: AppleEvent timed out. (-1712) I can't figure out why I'm getting a timeout error... anyone have any ideas?
1
0
177
2w
AppleScript help
Hello everyone, I would like to use AppleScript to transform a .csv file. To make things easier to understand, I'm attaching two files: 1- The original file in csv format 2- The file as I'd like it to look after I've run it through the script. Here are the steps involved 1-Open the file in numbers (Note: the file is located in the download folder). 2-Delete the first 6 lines 3-Delete all font styles and cell colors 4-Combine all cells in the nature of operation column of the same operation belonging to the same date in the first cell of the operation, deleting all spaces in the text is not necessary for each operation. 5- Delete all empty lines. I hope I've made my request clear. If any of you have the knowledge to do this, if it can be done at all, I'd be very grateful for their help in writing the script. Thank you in advance. 1.csv 2.csv
0
0
191
2w
Changing pad colour in Image Events
I'm trying to use Image Events instead of Photoshop to manipulate a bunch of images. I need to extend the canvas and have the padding be white. I've tried pad theImage to dimensions {545, 545} with pad color {65535, 65535, 65535} But that does nothing. If I remove the 'with pad colour...' part, it works but the pad defaults to black. I've looked everywhere, but there doesn't seem to be a solution. Is there one?
0
0
173
3w
AppleScript nd adobe indesign
I have a bunch of images sized 540px on the long side (some portrait, some landscape). The other side could be any size, but will be less than 540. There are no square images. I want to be able to choose a folder containing the images, and want the script to do the following for each image: Place it at the center of the current page of the active indesign document. Scrape the filename from the image (without the extension), apply the pre-existing Paragraph Style 'Caption' to the text, and center the text 36 points (not pixels) below the image. Group the image and the text. Then create a frame with white fill, 540x600 pixels in size, send it to back, center it with the group created above, and group them. I've been pulling my hair out. Just can't get it to work.
0
0
209
Jan ’25
AppleScript to Automate Envelope Printing
I have a VBScript routine to print envelopes by automating Word. This works just fine. Now I'm trying to do the same thing with AppleScript, also using the Word application. Here is what I have so far: set recipientAddress to text returned of (display dialog "Enter the recipient's address:" default answer "") -- Prompt for recipient city, state, and zip set recipientCityStateZip to text returned of (display dialog "Enter the recipient's city, state, and zip:" default answer "") -- Combine all address parts into a full address set fullAddress to recipientName & return & recipientAddress & return & recipientCityStateZip -- Create a new Word document and print the envelope set dialogResult to display dialog "To print envelope for:" & return & return & recipientName & return & recipientAddress & return & recipientCityStateZip & return & return & "Center envelope upside-down in printer with flap on left" & return & return & "Continue?" buttons {"Yes", "No"} default button 2 with icon caution if button returned of dialogResult is "Yes" then tell application "Microsoft Word" set wdDoc to make new document -- Print the envelope with the collected recipient address and hard-coded return address -- wdDoc's print out envelope(address:fullAddress, returnAddress:returnAddress) -- Close the document without saving close wdDoc saving no end tell end if What does NOT work is the commented line near the end of the script which starts with -- wdDoc's print out envelope... Either I am doing it wrong, or Word for Mac can't be automated that way. Can anyone help with this script, or at least suggest a different method to print an envelope on demand? Thanks...
1
0
437
Oct ’24
Correctly using NSAppleScript for Mail.app plugin
Context I'm working on a Mail.app plugin. I would like to disseminate plugin via AppStore. I'm interested in exposing a functionality to user enabling user to choose if plugin should apply to all or selected email account. My intention is to use AppleScript to get a list of available email accounts and expose the list to the end-user via SwiftUI Sourcing account information Apple Script I'm using the following AppleScript tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell The above generates expected results when executed using Script Editor. Swift Implementation This is still incomplete but shows the overall plan. // // EmailAccounts.swift import Foundation enum EmailScriptError: Error { case scriptExecutionError(String) } struct EmailAccounts { func getAccountNames() -> [String]? { let appleScriptSource = """ tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell """ var error: NSDictionary? var accountNames: [String] = [] // Create script object, exit if fails guard let scriptObject = NSAppleScript(source: appleScriptSource) else { return nil } // Execute script and store results, nil on error let scriptResult = scriptObject.executeAndReturnError(&error) if error != nil { return nil } // Iterate over results for index in 0...scriptResult.numberOfItems { if let resultEntry = scriptResult.atIndex(index) { if let resultString = resultEntry.stringValue { // Process result handling // accountNames.append(resultString) } } } return accountNames } } Questions Most important one, can I deploy the App on the App Store and use NSAppleScript as shown above? If yes can I use the script in the manner shown above or will I need to store the script in User > Library > Application Scripts location and source it from there. This is outlined in the Scripting from a Sandbox article by Craig Hockenberry, which I cannot link due to being hosted within a not-permitted domain. If yes what entitlements I need to give to the target. I understand that I wouldn't be able to use ScriptingBridge, which feels more robust but wouldn't permit me to deploy the app on the AppStore. My key objective is to programatically identify mail accounts available to Mail.app, if there is a wiser / easier way of doing that I would be more than receptive.
2
0
572
Oct ’24
Applescript text item delimiters not working
I have a string of the form “Mon 22nd April”. I’m trying to extract the day (i.e. Mon), the date (i.e. 22nd) and the month (i.e. April) using this Applescript: set originalDateString to “Mon 22nd April” -- Extract the components by splitting the string set AppleScript's text item delimiters to " " set dayOfWeekAbbrev to text item 1 of originalDateString set dayOfMonth to text item 2 of originalDateString set monthName to text item 3 of originalDateString When I run this on its own it works as expected: dayOfWeekAbbrev is set to “Mon” dayOfMonth is set to “22nd” monthName is set to “April” When I run this inside a bigger script involving Numbers, the text item delimiters fails to work, no compile or run time errors occur and I end up with: dayOfWeekAbbrev is set to “M” dayOfMonth is set to “o” monthName is set to “n” I.e the first three characters of the string. If I replace originalDateString with the literal string “Mon 22nd April” I get the same result. In other words, text items and being recognized as individual characters, no delimiter (or delimiter is null). Totally confused.
5
0
732
Oct ’24
macOS 15 – Is AppleScript a Gatekeeper workaround ?
I have tried to manually install binaries using Finder by clicking and dragging from the Desktop into "/usr/local/bin/". The binaries come with a collection of frameworks etc. All the binaries are adhoc signed. macOS asks for Admin credentials which is fine. But then, when I execute the binaries in Terminal, Gatekeeper shows the now expected "'[binary"] Not Opened Apple could not verify ........" etc. It shows that dialog for every component and requires user input 2-3 times to allow each component of which there are perhaps dozens. BUT, none of that happens if I install those binaries using AppleScript. So, it might have a call like this: do shell script "curl -L " & download_URL & " -o " & download_binary_zip with administrator privileges do shell script "unzip -o " & download_binary_zip & " -d " & usr_bin_folder with administrator privileges The resulting installs work perfectly. Is this intended ? Using both install methods requires Admin credentials. Why does using a script work but using Finder does not ?
4
0
763
Oct ’24
link to open endpoint security extensions via swiftUI
Hi Team, In previous macOS version, We were using this link to open system extension permission page programmatically for our swift app. x-apple.systempreferences:com.apple.preference.security?General In macos 15 (Sequoia), this pane is moved to system settings-> general->login Items and extensions->end point security extensions which is a modal/popup. Can you please share what should be link to open exact this popup for asking permissions.It appears when you click on i button against end point security extensions Based on apple script I could find following link but it opens login item & extensions pane, I want the next popup as above screenshot. "x-apple.systempreferences:com.apple.LoginItems-Settings.extension?extensionItems™
1
0
506
Sep ’24
Applescripting Chrome email
Hello all, I need some guidance please. Since recent security changes at Microsoft. AppleMail and Outlook on my very old MacBook (El Capitan) can no longer send/recieve emails as authorisation cannot bind. Before I could automate email (hotmail account) sending with AppleScript. I now use a web mail page for Outlook via Chrome but having to send manually. Can I get some advice on how to control, with AppleScript, the attached webpage to: open a new email add recipient in the To field add a subject attach a file send email. Or is there another solution (apart from buying a newer Mac!). Thank you
2
1
474
Sep ’24
script stopped working after upgrade to Sequoia
Hello, I don't know much about AppleScript, but I found this script on a Raycast site that dismisses Notification Center notifications. It worked great on Sonoma but has stopped working in Sequoia. Here is the code: tell application "System Events" tell process "NotificationCenter" if not (window "Notification Center" exists) then return set alertGroups to groups of first UI element of first scroll area of first group of window "Notification Center" repeat with aGroup in alertGroups try perform (first action of aGroup whose name contains "Close" or name contains "Clear") on error errMsg log errMsg end try end repeat -- Show no message on success return "" end tell end tell When using this to attempt to dismiss notifications, it returns the following error: Can’t get scroll area 1 of group 1 of window "Notification Center" of process "NotificationCenter". Invalid index. (-1719) Please help me fix it so it will run in Sequoia! This script was super useful.
1
2
560
Sep ’24
Applescript seems to run in Rosetta on M2
When calling a perl script from an apple script (by dropping a file on it), I get the error: Can't load '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' for module Encode: dlopen(/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle, 0x0001): tried: '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (no such file), '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) at /System/Library/Perl/5.34/XSLoader.pm line 96. at /Library/Perl/5.34/darwin-thread-multi-2level/Encode.pm line 12. When I call the script manually from terminal, it runs fine. Why is Applescript running as X86 on M2?
2
0
685
Oct ’24