Obtain layers that have been specifically chosen

Is there a method to retrieve an array of currently selected layers without the need to iterate through all the layers and potentially altering the selection? This differs from the question mentioned here.

function get_selected_layers()
{
  var layers = app.activeDocument.activeLayer;
 // only works with *last* selected layer
 // not *all* selected layers
}

var thelayers = get_selected_layers;
alert(thelayers);

Answer №1

Is it possible to obtain an array of selected artLayer objects in a native way? Not exactly. However, there is an Action Manager approach that allows you to retrieve descriptors of the selected layers, which can then be used to access the desired information. The following code snippet demonstrates how to extract an array containing names, indexes, and IDs of selected layers, with the ability to retrieve additional data by utilizing different getters on the layer descriptor (desc). Moreover, a function is included to select artLayers based on their IDs for obtaining the associated DOM objects. It's worth noting that this method works seamlessly with groups and artboards as well.

var layers = getSelectedLayersInfo();

// Select individual artLayers using their IDs
for (var i = 0; i < layers.length; i++) {
  selectByID(layers[i].id);
  alert(activeDocument.activeLayer.name);
}

// Reset selection afterwards
for (var i = 0; i < layers.length; i++) {
  selectByID(layers[i].id, true);
}


function getSelectedLayersInfo()
{
  var lyrs = [];
  var lyr;
  var ref = new ActionReference();
  var desc;
  var tempIndex = 0;
  var ref2;
  ref.putProperty(stringIDToTypeID("property"), stringIDToTypeID("targetLayers"));
  ref.putEnumerated(charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));

  var targetLayers = executeActionGet(ref).getList(stringIDToTypeID("targetLayers"));
  for (var i = 0; i < targetLayers.count; i++)
  {
    ref2 = new ActionReference();

    // Adjust index depending on existence of background layer   
    try
    {
      activeDocument.backgroundLayer;
      ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex());
      desc = executeActionGet(ref2);
      tempIndex = desc.getInteger(stringIDToTypeID("itemIndex")) - 1;

    }
    catch (o)
    {
      ref2.putIndex(charIDToTypeID('Lyr '), targetLayers.getReference(i).getIndex() + 1);
      desc = executeActionGet(ref2);
      tempIndex = desc.getInteger(stringIDToTypeID("itemIndex"));
    }

    lyr = {};
    lyr.index = tempIndex;
    lyr.id = desc.getInteger(stringIDToTypeID("layerID"));
    lyr.name = desc.getString(charIDToTypeID("Nm  "));
    lyrs.push(lyr);
  }

  return lyrs;
}

function selectByID(id, add) {
    if (add == undefined) add = false;
    var desc1 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putIdentifier(charIDToTypeID('Lyr '), id);
    desc1.putReference(charIDToTypeID('null'), ref1);
    if (add) desc1.putEnumerated(stringIDToTypeID("selectionModifier"), stringIDToTypeID("selectionModifierType"), stringIDToTypeID("addToSelection"));
    executeAction(charIDToTypeID('slct'), desc1, DialogModes.NO);
} // end of selectByID()

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

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

Is it possible for my WebDriver script to detect an event triggered by the webpage?

Is it feasible for my WebDriver script to carry out specific tests after a particular event is triggered on the webpage? Within the WebDriver script, I envision some form of event listener: document.addEventListener("hello", function(){ console.log(" ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

determining the quantity of dates

Is there a way to calculate the number of a specific day of the week occurring in a month using AngularJS? For example, how can I determine the count of Saturdays in a given month? Thank you. Here is the code snippet I have been working on: <!doctype ...

Strategies for including JavaScript variables in AJAX data

I have a basic webpage displaying employee names that can be dragged around using Jquery UI draggable. I am able to capture the "top" and "left" position of the dragged item and store it in a JavaScript variable. My next goal is to pass these two variable ...

Guide to implementing a personalized filter in AngularJS 1.6

I am struggling with injecting a custom filter, status, into my component. Below is the code for my component: function ClaimsListController(dpClaimsListService) { var ctrl = this; ctrl.claims = null; ctrl.searchCriterion = null; ctrl.l ...

Seeking assistance with coding a beginner-level Google Chrome extension

Currently, I am working on developing a basic Google Chrome extension with 2 or 3 browser actions. I have been using Selenium IDE to capture the necessary steps in Firefox that I need for my project. However, I am unsure of how to translate these recorde ...

What is the solution to the problem "How can you resolve the issue where 'Cannot set property 'ref' of undefined' occurs"?

My goal is quite simple - I just want to retrieve data from Cloud Firestore. Below is the code snippet I am using: import React from 'react'; import firebase from "react-native-firebase"; export default class newsFeed extends React.Component { ...

Response from the server to multiple asynchronous XMLHttpRequests

I'm in the process of creating a Web Application that involves making multiple simultaneous XHR calls using Ajax instead of native Javascript. $.ajax({ type: 'POST', url: 'Services/Service.asmx/MyFunction', contentTyp ...

Update your code to use the fetch API instead of axios

Looking to switch my axios post call to a fetch call: export async function createFriend ({ let myData = new FormData() myData.append('name', name) myData.append('age', age) const response = await axios.post('/myApi/friends ...

Are JS commands enough for using Node.js dom APIs like jsdom and cheerio, or do I have to rely on jQuery for these tasks?

Is there a DOM API available for Node.js that allows me to use pure JavaScript commands? I prefer not to use jQuery as I already have existing code in vanilla JS. ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

What are some tips for using copy and paste with Protractor on a Mac using Chrome?

Is there a way to utilize copy and paste functionality with Protractor on a MAC using Chrome? newInput.sendKeys(protractor.Key.chord(browser.controlKey, "a")); newInput.sendKeys(protractor.Key.chord(browser.controlKey, "c")); newInput.sendKeys(protractor. ...

Tips for utilizing the setInterval function in javascript to update the background color of the body

Currently, I am tackling a project for my course and I am seeking to modify the body's background color on my website randomly by leveraging the setInterval technique in my JavaScript file. Any suggestions on how to achieve this task? ...

Trouble arises when adding HTML elements to a Content Editable Div. Any text inputted after programmatically inserting HTML content will merge with the last HTML tag instead

https://i.sstatic.net/bKIVm.pngI am currently working on a project that involves creating message templates within an app. Users have the ability to add placeholders for fields like names to these templates by clicking a button. They can also remove these ...

The loading time for the Ajax request is unreasonably slow

I am currently managing a website dedicated to League of Legends. My main task involves requesting statistics from the Riot Games API based on a player's name, which returns the information in JSON format. However, there is a significant delay in load ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route t ...

What is the process for determining the estimated location of a queued event within a JavaScript Engine's event queue?

Imagine a multitude of events being created and added to the event queue of a Javascript engine. Are there any techniques or recommended practices in the industry to predict the order in which a specific event will be added to the queue? Any knowledge or ...