Sub topic 17
Automating smart object actions with scripts
What this chapter covers
This chapter assumes you can create, edit, and replace smart objects by hand. It also assumes you have run a script from File > Scripts > Browse, and that you read basic JavaScript. You will learn how to run the same smart object commands from ExtendScript, how to replace contents in a batch, and which errors to expect.
Scripting matters when you repeat the same step many times. Examples are converting every layer in a set of documents, or swapping artwork into many mockups. A script does these steps the same way every time.
How Photoshop scripting reaches smart objects
Photoshop's ExtendScript is JavaScript with a Photoshop object model. The document object model covers most layer work. Many smart object commands are not in that model, so scripts call them through the Action Manager. The Action Manager is the lower-level interface that Photoshop uses for menu commands and recorded actions.
An Action Manager call has three parts:
- An event ID, which names the command. You convert a string to an ID with
stringIDToTypeID. - A descriptor, which holds the command's settings. It can be
undefinedwhen the command needs none. - A dialog mode, which says whether Photoshop shows a dialog.
DialogModes.NOsuppresses it.
Smart object commands use the term "placed layer" internally. This is an older name for smart objects, so you will see it in event names.
| Menu command | Event string ID |
|---|---|
| Layer > Smart Objects > Convert to Smart Object | `newPlacedLayer` |
| Layer > Smart Objects > Edit Contents | `placedLayerEditContents` |
| Layer > Smart Objects > Replace Contents | `placedLayerReplaceContents` |
| Layer > Smart Objects > Rasterize | `rasterizeLayer` with a target of the layer |
The first two IDs are the ones this chapter's examples use. Check any other ID in your own Photoshop version before relying on it. The next section shows how.
Convert the selected layers
The shortest useful script converts the selected layers to a smart object. It is the same as the menu command.
// Convert the active layer(s) to a smart object
// (same as Layer > Smart Objects > Convert to Smart Object)
executeAction(stringIDToTypeID("newPlacedLayer"), undefined, DialogModes.NO);If several layers are selected, Photoshop packs them into one smart object. That matches the manual behavior. The script acts on the current selection, so it fails if there is no document open.
Edit the contents
This script opens the embedded contents of the selected smart object in its own window.
// Open the contents of the active smart object layer for editing
// (same as Layer > Smart Objects > Edit Contents)
executeAction(stringIDToTypeID("placedLayerEditContents"), undefined, DialogModes.NO);The contents open as a separate document. The parent document does not change until you save the contents document. Saving it updates the smart object. The command only works when the active layer is a smart object, so the script should check first.
Check the layer before acting
A script that assumes a smart object will stop with an error on any other layer. The kind property of an art layer tells you what it is.
// Run Edit Contents only if the active layer is a smart object
if (app.documents.length === 0) {
alert("Open a document first.");
} else {
var layer = app.activeDocument.activeLayer;
if (layer.kind === LayerKind.SMARTOBJECT) {
executeAction(stringIDToTypeID("placedLayerEditContents"), undefined, DialogModes.NO);
} else {
alert("The active layer is not a smart object.");
}
}Groups are layer sets, not art layers, so they have no kind value. A group as the active layer needs its own check. Without one, the script reads kind as undefined and falls to the else branch. That gives the right message but for a different reason.
Replace contents from a file
Replacing contents is the core of mockup automation. The replace command takes a descriptor that holds the path of the new file.
// Replace the contents of the active smart object with a file
function replaceContents(file) {
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), file);
executeAction(stringIDToTypeID("placedLayerReplaceContents"), desc, DialogModes.NO);
}
var layer = app.activeDocument.activeLayer;
if (layer.kind !== LayerKind.SMARTOBJECT) {
alert("Select a smart object layer first.");
} else {
var picked = File.openDialog("Choose the replacement image");
if (picked) {
replaceContents(picked);
}
}File.openDialog returns null when the user cancels, so the script tests the result before using it. The replacement keeps the position, transform, and smart filters of the layer, as it does in the interface. The new image is fitted to the old bounds the way the menu command fits it.
Be careful with the descriptor key. charIDToTypeID("null") is the standard key for the target path. A wrong key makes the command fail or ignore the file.
Batch replacement for mockups
You can wrap the function in a loop to produce one output per image in a folder. This sketch assumes the document has a smart object layer named Artwork.
// Export one JPEG per image in a chosen folder, using a mockup with a smart object named "Artwork"
function replaceContents(file) {
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), file);
executeAction(stringIDToTypeID("placedLayerReplaceContents"), desc, DialogModes.NO);
}
var doc = app.activeDocument;
var folder = Folder.selectDialog("Choose the folder of images");
if (folder) {
var files = folder.getFiles(/\.(jpg|jpeg|png|tif|tiff)$/i);
doc.activeLayer = doc.artLayers.getByName("Artwork");
for (var i = 0; i < files.length; i++) {
replaceContents(files[i]);
var out = new File(folder + "/mockup_" + (i + 1) + ".jpg");
var options = new JPEGSaveOptions();
options.quality = 10;
doc.saveAs(out, options, true, Extension.LOWERCASE);
}
}The true argument saves a copy. The mockup file itself stays open and unchanged on disk. The script writes mockup_1.jpg, mockup_2.jpg, and so on into the chosen folder.
getByName throws an error if no layer has that name. It also looks only at top-level layers of the collection, so a smart object inside a group is not found this way. Select such a layer by hand before running the script, or wrap the lookup in try and catch and tell the user what is missing.
Find the event IDs you need
Not every smart object command has a documented ID in a form you can look up quickly. A reliable method is to record the command in Photoshop and read the generated code.
- Open the Actions panel and start recording a new action.
- Run the menu command once, for example Layer > Smart Objects > Export Contents.
- Stop recording.
- Use the Scripting Listener plug-in, or Adobe's Script Listener tools, to log the command as code. The log shows the event ID and descriptor keys.
The logged code often uses long, repetitive calls. You can shorten it, but keep the IDs and keys unchanged.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "General Photoshop error occurred" | The command does not apply to the current selection, such as Edit Contents on a normal layer | Check `layer.kind` first |
| Replace runs but nothing changes | Wrong descriptor key or an invalid file object | Use `charIDToTypeID("null")` and test that the file exists |
| Script stops at a dialog | `DialogModes.NO` was left out or a dialog from the file type opens | Pass `DialogModes.NO` and test with one file type at a time |
| Layer not found by name | Layer is inside a group, or the name differs | Select the layer by hand or search the group |
| Linked smart object does not update | The linked file is missing or moved | Fix the link before running, as covered in the chapter on linked files |
Limits of scripting this way
Action Manager event IDs are not part of the formal object model. Adobe can change them between versions, so keep scripts short, add comments naming the menu command, and retest after an upgrade. Scripts also run on the open document on screen, so very large batches are slow and benefit from closing unneeded documents.
Scripting does not change what a smart object is. The script gives you speed and repeatability, and the nondestructive behavior comes from the smart object itself.
Exercise
A script calls placedLayerEditContents and Photoshop reports a general error. The active layer is a regular pixel layer. What check should the script add, and what property does it use?
Show answer
Before running the command, the script should confirm the active layer is a smart object by testing app.activeDocument.activeLayer.kind === LayerKind.SMARTOBJECT. If the test fails, it should show a message or skip the layer instead of calling the command.
Exercise
In the batch mockup script, why is true passed to saveAs, and what would happen to the mockup document if it were not?
Show answer
The true argument makes saveAs save a copy. The open mockup document keeps its original name and stays tied to its original file. Without it, the document would become the last JPEG, so the open document would no longer be the mockup file.