Issue encountered when attempting to execute a JavaScript AppleScript from another JavaScript AppleScript due to permissions error

I am in the process of organizing my .applescript files by separating them into different ones for better organization.

Within my JS AppleScript file named Test.applescript, I am attempting to execute another JS AppleScript file called

Group Tracks Dependency.applescript
. My goal is to pass a parameter into the dependency script and retrieve a return value from it, which creates an array of arrays of iTunes tracks.

In Test.applescript:

(function() {
    var app = Application('iTunes');
    app.includeStandardAdditions = true;

    app.doShellScript('Group Tracks Dependency.applescript');

    return "Done";
})();

// For quick logging
function log(obj) {
    this.console.log(obj);
}

In Group Tracks Dependency.applescript:

(function(selection) {

    return getGroupsOfTracks(selection);

    function getGroupsOfTracks(originalTracksArray) {
        if (originalTracksArray == null || originalTracksArray.length == 0) 
            return null;

        var tracks = originalTracksArray.slice();
        var groups = [];
        while (true) {
            var group = [];
            group.push(tracks[0]);
            tracks = tracks.slice(1);

            while (true) {
                if (!tracks[0]) break;
                if (tracks[0].album() != group[0].album())
                    break;
                if (tracks[0].artist() != group[0].artist())
                    break;
                if (tracks[0].discNumber() != group[0].discNumber())
                    break;
                group.push(tracks[0]);
                tracks = tracks.slice(1);
            }

            groups.push(group);
            if (!tracks[0]) break;
        }

        return groups;
    }
})();

Upon running the Test script, I encounter an error at line 5 (app.doShellScript):

Error on line 5: Error: A privilege violation occurred.

I am seeking a solution to bypass this issue. Additionally, I want to make these scripts easily accessible for others to download and use on their own iTunes libraries in the future (although the current setup may not be user-friendly).

If there is no workaround for this problem, would importing another JS AppleScript file serve as a viable solution?

Answer №1

Perhaps you're faced with a challenge that .doShellScript can't solve on its own.

One alternative recommended by Apple is to utilize a Script Library, as outlined in detail at https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-11.html#//apple_ref/doc/uid/TP40014508-CH110-SW1

Regrettably, script libraries do have limitations when it comes to passing complex variables.

Another approach worth considering is using require, which can be implemented following the instructions provided at https://github.com/dtinth/JXA-Cookbook/wiki/Importing-Scripts

Answer №2

I've found a solution that works well for me using Script Editor 2.8.1 (183.1) on OSX 10.11.4:

  1. Begin by creating a main JXA Script file
  2. Next, create a JXA Script Library file

Both of these files must be saved as compiled script files (.scpt)

It's important to note that the statement "Unfortunately a script library has constraints where you can only pass simple variables" is incorrect.

You have the flexibility to call any functions from the Script Library file in any JXA script.

In your main script file, which I'll name "Get iTunes Group Selection.scpt":

var app = Application('iTunes');
app.includeStandardAdditions = true;

var myLib = Library("My JXA Lib")

var selectionArr = app.selection()   // ### Change as needed ###
var groupArr = myLib.getGroupsOfTracks(selectionArr)
groupArr

~~~~~~~~~~~~~~~~~~~~~

Now, in a separate script file that needs to be saved as:

~/Library/Script Libraries/My JXA Lib.scpt

function getGroupsOfTracks(originalTracksArray) {
        if (originalTracksArray == null || originalTracksArray.length == 0) 
            return null;

        var tracks = originalTracksArray.slice();
        var groups = [];
        while (true) {
            var group = [];
            group.push(tracks[0]);
            tracks = tracks.slice(1);

            while (true) {
                if (!tracks[0]) break;
                if (tracks[0].album() != group[0].album())
                    break;
                if (tracks[0].artist() != group[0].artist())
                    break;
                if (tracks[0].discNumber() != group[0].discNumber())
                    break;
                group.push(tracks[0]);
                tracks = tracks.slice(1);
            }

            groups.push(group);
            if (!tracks[0]) break;
        }

        return groups;
 }

Answer №3

It has been a couple of years...

I encountered some issues with JXA and doShellScript when attempting to execute the script with Application("Finder"). These problems were resolved by running the script using Application.currentApplication() instead. Therefore, I utilized

const finder = Application("Finder")
for Finder-specific tasks and
const app = Application.currentApplication()
for script execution.

For instance:

//test1.scpt
function run() {    
    const app = Application.currentApplication()
    app.includeStandardAdditions = true
    app.doShellScript("osascript ~/Desktop/test2.scpt")
}
//test2.scpt
function run() {
    const app = Application.currentApplication()
    app.includeStandardAdditions = true
    
    app.displayDialog("foo")
    app.doShellScript("osascript -e 'display dialog \"bar\"'")
}

When executing test1.scpt, it generates two dialogs: foo and `bar.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

How can I efficiently transfer information between AngularJS modules?

Angular offers the flexibility of creating independent Modules that can be reused in various parts of your application. Imagine having a module dedicated to managing lists, which you want to use across your entire application and populate in different ways ...

Accordion featuring collapsible sections

Looking to build an accordion box using Javascript and CSS. The expanded section should have a clickable link that allows it to expand even further without any need for a vertical scroll bar. Any ideas on how this can be achieved? Thank you ...

How can I trigger a mousedown event on mobile devices without using jQuery?

Can I implement a straightforward mousedown/mouseup event in an Angular-based mobile app? While utilizing ngTouch for swiping, I've noticed it lacks support for a 'while-pressed' event. I've found that ngMousedown is ineffective on to ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

JavaScript allows for selecting individual IDs by their corresponding numbers

Looking to retrieve numerical IDs <div class="user-view"> <div class="show_user_div"> <div class="disp"> <a href="/profile/name1/">name1</a><br /> <span id="show_a_3"> <a id="ref_show(3)">Show Details</ ...

Include token in src tag requests Angular version 8

In the process of developing a website, I have encountered a challenge. I am creating a platform where users can access another website I am currently working on after they log in. Once authorized, users receive a JWT token which is sent in the header with ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Issue with Stack Divider not appearing on Chakra UI card

I'm currently designing a card element using Chakra UI. However, I've noticed that the Stack Divider in the Card Body isn't displaying as expected. Is there a specific way it needs to be structured for it to show up? For example, should I se ...

Steps for creating a PDF file from an HTML page using JavaScript coding

I'm developing an HTML5 hybrid iPad app and need to create a PDF file of a report generated on one of the pages. I would like to save this PDF on the iPad. Can you provide assistance with achieving this task? I am utilizing JavaScript and mobile jQuer ...

How can you prevent the upload button from being clicked while a file is being uploaded and

By chance, I stumbled upon an issue that could potentially lead to a major problem with my application. I have developed an application where users can upload videos. Check out the Application here The main concern is that when a user uploads a video and ...

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

Using jQuery and AJAX to submit a dynamic form

I am currently facing an issue with cloning a HTML drop down list using jQuery. The main problem I am encountering is that there seems to be no restriction on the number of cloned sections, and I need to store all these sections in a mySQL database. How c ...

Exploring the functionality of $.param in jQuery

After extensive research online, I found that the most helpful information was on the official jQuery site. Here is the code snippet I am currently using: var param = { branch_id : branch_id}; var str = $.param(param); alert(str); However, when I log or ...

What is the best way to create titles with a background?

My goal is to have a title overlay an image with specific width and the text displayed in blocks. To better illustrate, here's an example: I prefer to achieve this effect using CSS; however, I am open to utilizing Javascript if needed. ...

Check if the browser is compatible with the FREEZE and RESUME lifecycle events

Is there a method to determine if a browser is capable of registering the freeze and resume lifecycle events? Even after checking with Modernizr, a reliable JS library, it appears that these events are not supported. Although extremely beneficial, Safari ...