Sub topic 15
Automating replacement and export with a script
Once a mockup is built, the repeated work is mechanical: select the placeholder, run Replace Contents, export, and repeat for each design. This chapter turns that loop into an ExtendScript file you can run from Photoshop.
This chapter assumes you have:
- a mockup document with a smart object placeholder named
Artwork(see the chapters on creating the placeholder and Replace Contents) - an understanding of embedded versus linked smart objects
- a consistent color profile and resolution for your artwork
- basic JavaScript: variables, functions, loops and conditions
What the script does
ExtendScript is Adobe's JavaScript dialect. It follows the old ES3 standard, so there is no let, const, arrow functions or built-in JSON. Use var and plain function declarations.
The script does the same steps you do by hand.
Replace Contents has no simple DOM method in the scripting API. You call it through the Action Manager, the lower-level interface that Photoshop's own actions use. That is why the code uses executeAction and ID conversion functions.
The single-file script
This script handles one artwork file. It works when Artwork is a top-level layer.
#target photoshop
var doc = app.activeDocument;
var artworkFile = new File("~/mockups/art/poster-01.png");
var outFile = new File("~/mockups/out/poster-01.jpg");
// Select the placeholder smart object by layer name (top-level layer).
doc.activeLayer = doc.layers.getByName("Artwork");
// Replace its contents with the new artwork file.
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), artworkFile);
desc.putInteger(charIDToTypeID("PgNm"), 1);
executeAction(stringIDToTypeID("placedLayerReplaceContents"), desc, DialogModes.NO);
// Save a JPEG copy of the finished mockup.
var opts = new JPEGSaveOptions();
opts.quality = 10;
doc.saveAs(outFile, opts, true, Extension.LOWERCASE);The important lines:
#target photoshoptells the ExtendScript Toolkit or the File > Scripts menu which application should run the file.getByNamesearches only the top level of the layer stack. It throws an error if the name is missing, and it does not look inside groups.placedLayerReplaceContentsis the event ID for Replace Contents. It acts on the active layer, so you must select the layer first.putPathwith"null"supplies the replacement file.PgNmis the page number, which matters for multipage PDFs and is 1 for ordinary images.DialogModes.NOsuppresses the file dialog and any import prompts.- The
trueargument tosaveAsmeans "save as a copy". The PSD stays untouched and keeps its name. JPEGSaveOptions.qualityranges from 0 to 12. The value 10 is a reasonable default for review images.
Making it robust
Real mockups put the placeholder inside groups, such as Product > Front > Artwork. You also need to check that the layer really is a smart object. Two helper functions handle both.
function findLayer(container, name) {
for (var i = 0; i < container.layers.length; i++) {
var layer = container.layers[i];
if (layer.name === name) {
return layer;
}
if (layer.typename === "LayerSet") {
var found = findLayer(layer, name);
if (found) {
return found;
}
}
}
return null;
}
function replaceContents(layer, file) {
app.activeDocument.activeLayer = layer;
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), file);
desc.putInteger(charIDToTypeID("PgNm"), 1);
executeAction(stringIDToTypeID("placedLayerReplaceContents"), desc, DialogModes.NO);
}findLayer walks the stack recursively. A group has typename equal to "LayerSet", and its own layers collection holds its children. findLayer returns null instead of throwing, so the calling code can show a clear message.
Layer names are not unique in Photoshop. If two layers are named Artwork, the function returns the first one it meets. Give each placeholder a distinct name such as Artwork Front and Artwork Back.
The batch script
This version processes every image in a folder and writes one JPEG per file.
#target photoshop
function findLayer(container, name) {
for (var i = 0; i < container.layers.length; i++) {
var layer = container.layers[i];
if (layer.name === name) {
return layer;
}
if (layer.typename === "LayerSet") {
var found = findLayer(layer, name);
if (found) {
return found;
}
}
}
return null;
}
function replaceContents(layer, file) {
app.activeDocument.activeLayer = layer;
var desc = new ActionDescriptor();
desc.putPath(charIDToTypeID("null"), file);
desc.putInteger(charIDToTypeID("PgNm"), 1);
executeAction(stringIDToTypeID("placedLayerReplaceContents"), desc, DialogModes.NO);
}
function isArtwork(item) {
return item instanceof File && /\.(png|jpe?g|tiff?|psd)$/i.test(item.name);
}
function baseName(file) {
return decodeURI(file.name).replace(/\.[^.]+$/, "");
}
function main() {
var doc = app.activeDocument;
var inFolder = new Folder("~/mockups/art");
var outFolder = new Folder("~/mockups/out");
if (!outFolder.exists) {
outFolder.create();
}
var target = findLayer(doc, "Artwork");
if (!target) {
alert("No layer named Artwork was found.");
return;
}
if (target.kind !== LayerKind.SMARTOBJECT) {
alert("The layer named Artwork is not a smart object.");
return;
}
var files = inFolder.getFiles(isArtwork);
var done = 0;
for (var i = 0; i < files.length; i++) {
replaceContents(target, files[i]);
var opts = new JPEGSaveOptions();
opts.quality = 10;
opts.embedColorProfile = true;
var outFile = new File(outFolder + "/" + baseName(files[i]) + ".jpg");
doc.saveAs(outFile, opts, true, Extension.LOWERCASE);
done++;
}
alert("Exported " + done + " mockups.");
}
var savedDialogs = app.displayDialogs;
app.displayDialogs = DialogModes.NO;
try {
main();
} finally {
app.displayDialogs = savedDialogs;
}Design choices worth noting:
main()lets the script usereturnto stop early. A top-levelreturnis a syntax error in ExtendScript.inFolder.getFiles(isArtwork)passes a filter function, so folders and stray files such as.DS_Storeare skipped.baseNameremoves the extension and decodes%20sequences, soSummer Sale.pngbecomesSummer Sale.jpgand notSummer%20Sale.jpg.- The
try/finallyblock restores your dialog setting even if an error occurs partway through. - The script never saves the PSD. Each replacement overwrites the previous one in memory, and
saveAswith the copy flag leaves the source document unchanged.
Running the script
- Save the code as
replace-and-export.jsx. - Open the mockup PSD so it is the active document.
- Choose File > Scripts > Browse and select the file.
To make the script appear in the Scripts menu, copy it into Photoshop's Presets/Scripts folder and restart the application.
Color and size in automated exports
The script does not fix color problems. A few settings decide whether a batch comes out consistent:
saveAswithembedColorProfile = truetags the file with the document's profile but does not convert it. If the mockup is in Adobe RGB and the web needs sRGB, convert the document once before running the script, or use a Save for Web workflow.- Replace Contents scales the new artwork to fit the placeholder's bounds. Artwork with a different aspect ratio ends up letterboxed or mis-sized. Prepare all artwork to the same dimensions and ratio beforehand.
- Low-resolution artwork is scaled up and looks soft. Check the source pixel dimensions against the placeholder size before a large run.
- For linked smart objects, the path stored in the PSD must still resolve. Moving the linked folder breaks the link, and the script then exports stale or missing content.
Common script errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Error 8800: General Photoshop error` on replace | The active layer is not a smart object, or the file path is wrong | Check `layer.kind` and confirm `file.exists` before replacing |
| `getByName` throws "No such element" | The layer is inside a group or is misnamed | Use `findLayer` and match the name exactly, including case |
| Output files overwrite each other | Two inputs share a base name, such as `a.png` and `a.jpg` | Include the extension in the output name or process one format |
| A dialog stops the batch | Photoshop prompts for a missing profile or a font | Set `app.displayDialogs = DialogModes.NO` and fix profiles first |
| Replacement ignores the page number | A multipage PDF opens on page 1 | Change the `PgNm` value to the page you need |
| Output looks the same for every file | The script replaced the contents but exported the wrong document | Make sure `app.activeDocument` is the mockup, not an opened artwork file |
A useful habit is to test the script on two files first. Open the first output and confirm the transforms, shadows and smart filters survived, then run the full folder.
Exercise
Your mockup keeps the placeholder in a group called Front, and the batch script reports "No such element" at the line doc.layers.getByName("Artwork"). Explain why, name the function from this chapter that fixes it, and say how to avoid replacing the wrong layer when two groups both contain a layer named Artwork.
Show answer
getByName only searches the top level of the layer stack, so it does not see layers nested inside the Front group. The fix is the recursive findLayer function, which descends into each layer whose typename is "LayerSet" and returns null if nothing matches. When two groups contain the same layer name, findLayer returns the first match it meets, so rename the placeholders to be unique (for example "Artwork Front" and "Artwork Back"), or search the specific group's layers collection, such as findLayer(doc.layers.getByName("Front"), "Artwork").