Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document.

Here is the code:

function getAllLayersInLayerSets(layerNodes) {

 var retList = [];

 for (var i=0; i<layerNodes.length; i++) {

    if(layerNodes[i].layerSets.length > 0)
    {
        var tmp = getAllLayersInLayerSets(layerNodes[i].layerSets);

        var j = (tmp == null) ? -1 : tmp.length-1;
        while(tmp && j>=0)
        {
            retList.push(tmp[i]);
            j--;
        }
    }
    for(var layerIndex=0; layerIndex < layerNodes[i].artLayers.length; layerIndex++) 
    {
        var layer=layerNodes[i].artLayers[layerIndex];
        retList.push(layer);
    }

}

return retList;  
}

Appreciate any help or discussion on this topic.

Answer №1

Although this discussion is from a while back, I wanted to share some helpful information.

I recently needed a function to retrieve all ArtLayers within a Photoshop composition, even those located within groups. The original function provided was returning undefined for me, so I made some modifications and managed to get it working properly.

var document = app.activeDocument;
var layersArray = [];
var layersArray = getAllLayers(document, layersArray);

function getAllLayers(doc, array){
    for (var i = 0; i < doc.layers.length; i++){
        var currentLayer = doc.layers[i];
        if (currentLayer.typename === "ArtLayer"){
            array.push(currentLayer);
        }else{
            getAllLayers(currentLayer, array);
        }
    }
    return array;
}

Answer №2

Expanding on Ghoul Fool's original post, this script specifically targets only the visible art layers in the active document. :P

// Retrieve all visible layers in the active document
var sourceDocument = app.activeDocument;
var visibleLayers  = [];
var visibleLayers  = collectAllVisibleLayers(sourceDocument, visibleLayers);

// Display total number of visible layers found
alert(visibleLayers.length);


// Function to recursively gather all visible art layers in a given document
function collectAllVisibleLayers(parent, allVisibleLayers)
{
    for (var m = 0; m < parent.layers.length; m++)
    {
        var currentLayer = parent.layers[m];
        if (currentLayer.typename === "ArtLayer")
        {
            if(currentLayer.visible)
            {
                allVisibleLayers.push(currentLayer);
            }
        }
        else
        {
            collectAllVisibleLayers(currentLayer, allVisibleLayers);
        }
    }
    return allVisibleLayers;
}

Answer №3

function chooseAllLayers() {
    var desc15 = new ActionDescriptor();
    var ref11 = new ActionReference();
    ref11.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Itms'), charIDToTypeID('Trgt'));
    desc15.putReference(charIDToTypeID('null'), ref11);
    executeAction(stringIDToTypeID('chooseAllLayers'), desc15, DialogModes.NO);
}

Answer №4

In order to access all the layers, including sub layers, a recursive function is required.

var layerCollection = new Array();
var allLayers = collectAllLayers(app.activeDocument, 0);


function collectAllLayers (parentLayer, level)
{
  for (var i = parentLayer.layers.length - 1; i >= 0; i--)
  {
    var currentLayer = parentLayer.layers[i];
    if (currentLayer.typename != "ArtLayer")
    {
      layerCollection.push(level + currentLayer.name);
      collectAllLayers(currentLayer, level + 1)
    }
  }
}

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

Is there a way to verify the existence of a specific error in the console?

There seems to be a conflict between a WordPress plugin or code left behind by the previous programmer, causing the WordPress admin bar to always remain visible. While no error is triggered for admins, visitors may encounter a console error. My goal is to ...

Load a 3D object or model using three.js and then make modifications to its individual components

Seeking advice on displaying and manipulating a 3D model of a robot arm in a browser. How can I load the model into three.js to manipulate all the sub-parts of the robot arm? Using Inventor, I have an assembly of a rotary motor and a shaft exported as an ...

How can I trigger an onclick event for a link automatically upon loading in Laravel?

I am presenting the link below: <a href="javascript:void(0)" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a> My goal is for it to change the language of the page (which occu ...

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

The issue arises when attempting to execute an Ajax function within a JQuery append method, causing malfunction

My JQuery append function is calling an ajax function within the onChange method. Here is my code snippet: var data='<?php echo $data; ?>'; var tambah=1; var txt=1; function add_fullboard_dalam_kota(){ function showU(str) { ...

What causes the off-canvas menu to displace my fixed div when it is opened?

Using the Pushy off-canvas menu from GitHub for my website has been great, but it's causing some trouble with my fixed header. When I scroll down the page, the header sticks perfectly to the top, but once I open the off-canvas menu, the header disappe ...

Building a 3D Earth model using three.js for WebGL applications

I found a code online, but it doesn't seem to work. Can someone provide me with the HTML code needed to make it run in my browser? The original code was sourced from this website (github repository) Github code repository https://github.com/turban/ ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Mocking a React component with Jest's MockImplementation

Currently, I am in the process of testing a react component that renders another component. This secondary component makes an API call to fetch data which is then displayed on the screen. My goal is to understand how I can mock this particular component&ap ...

Troubleshooting EJS Relative Path Problem when Using "include" in an HTML Document

I'm encountering an issue with my "index.ejs" file... The current content of the ejs file: <!DOCTYPE html> <html lang="en" dir="ltr"> <!-- THIS SECTION IS FOR <head> TAG THAT WILL BE STORED INSIDE "so_ ...

Chat Bot - EmbedMessage

JavaScript is still very new to me and I find the actual code quite challenging to grasp. However, I do have one specific question - how can I display the "cahbResponses" in a MessageEmbed? Despite consulting the Discord JS guides on MessageEmbeds, I' ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Error: The method .map is not a valid function in this context

I've decided to build a small To-Do app in order to enhance my knowledge of ReactJS and React Hooks. However, I'm facing an issue with the list.map() function that I'm using. The error message keeps saying that it's not a function, but ...

I'm looking to create an array of tags that contain various intersecting values within objectArray

Initially const array = [ { group: '1', tag: ['sins'] }, { group: '1', tag: ['sun'] }, { group: '2', tag: ['red'] }, { group: '2', tag: ['blue'] }, { grou ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

What is the list of NPM packages already included in the AWS Lambda execution environment?

I was surprised to discover that the aws-sdk NPM module comes preinstalled in AWS Lambda using nodejs8.10. I couldn't find any information online about this. Are there other node.js modules that are also pre-installed in AWS Lambda? ...

What is the process for integrating this graph using highcharts?

Check out this link for more information on investment decision-making. There is a visually appealing graph and pie chart featured in the section about Investment Decision-Making in 2016. After noticing that it was created using Highcharts, I wanted to c ...

Troubleshooting: Browser fails to update after CSSStyleRule modification using JavaScript

When making changes to CSS properties of elements using JS methods like CSSStyleSheet, insertRule, deleteRule, or CSSStyleRule.style.setProperty(), I noticed that the underlying CSS is updated but the page does not reflect these changes immediately. The c ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...