This 1.1 version adds a prompt to replace an existing file or to cancel.
EDIT – I have updated the code to a v1.2 which only uses the visible layer names:
/*
Save single JPEG using all visible layer names.jsx
v1.2, 4th March 2023, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/export-jpg-and-combining-the-visual-layer-names-to-create-the-file-name/td-p/13617072
*/
#target photoshop
(function () {
// Set the doc and layer variables
var doc = app.activeDocument;
var docPath = doc.path;
var layers = doc.layers;
// Create an empty array to hold the layer names
var layerNames = [];
// Backwards loop over layers and push the layer names to the array variable
for (var i = layers.length - 1; i >= 0; i--) {
if (layers[i].visible === true) {
layerNames.push(layers[i].name);
}
}
// Join the layer names with an underscore separator
var joinLayerNames = layerNames.join("_");
// RegEx replace word spaces for underscores
var fileName = joinLayerNames.replace(/ /g, '_');
var jpgSave = new File(docPath + "/" + fileName + ".jpg");
// Check for existing file
if (jpgSave.exists) {
// true = 'No' as default active button
if (!confirm("File exists, overwrite: Yes or No?", true))
return;
}
// Setup the save options
var jpgOptns = new JPEGSaveOptions();
jpgOptns.formatOptions = FormatOptions.STANDARDBASELINE;
jpgOptns.embedColorProfile = true;
jpgOptns.matte = MatteType.NONE;
jpgOptns.quality = 10;
doc.saveAs(jpgSave, jpgOptns, true, Extension.LOWERCASE);
}());