Give an example. Upload your PSD file.
Noticed that scripts (mine and yours) remove the black layer if there is one RGB pixel (0,0,1) in it, which is wrong. Corrected my script
// important, the active layer must not have to be a group.
var inv = false; // depends on channels settings. true = masked areas, false = selected areas. check what you have.
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("count"));
r.putEnumerated(stringIDToTypeID("layer"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
var count = executeActionGet(r).getInteger(stringIDToTypeID("count"));
var n = 0;
try { app.activeDocument.backgroundLayer; } catch(e) { n = 1; ++count; }
var r_idx = new ActionReference();
var do_it = false;
for (var i = count-1; i >= n; i--)
{
var r = new ActionReference();
r.putIndex(stringIDToTypeID("layer"), i);
if (executeActionGet(r).getInteger(stringIDToTypeID("layerKind")) != 1) continue;
var d = new ActionDescriptor();
var r = new ActionReference();
r.putProperty(stringIDToTypeID("channel"), stringIDToTypeID("selection"));
d.putReference(stringIDToTypeID("null"), r);
var d1 = new ActionDescriptor();
var r1 = new ActionReference();
r1.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("gray"));
r1.putIndex(stringIDToTypeID("layer"), i);
d1.putBoolean(stringIDToTypeID("invert"), inv);
d1.putReference(stringIDToTypeID("to"), r1);
d1.putEnumerated(stringIDToTypeID("calculation"), stringIDToTypeID("calculationType"), stringIDToTypeID("normal"));
var r2 = new ActionReference();
r2.putEnumerated(stringIDToTypeID("channel"), stringIDToTypeID("channel"), stringIDToTypeID("gray"));
r2.putIndex(stringIDToTypeID("layer"), i);
d1.putReference(stringIDToTypeID("source2"), r2);
d1.putBoolean(stringIDToTypeID("invertSource2"), inv);
d.putObject(stringIDToTypeID("to"), stringIDToTypeID("calculation"), d1);
executeAction(stringIDToTypeID("set"), d, DialogModes.NO);
var r = new ActionReference();
r.putProperty(stringIDToTypeID("property"), stringIDToTypeID("selection"));
r.putEnumerated(stringIDToTypeID("document"), stringIDToTypeID("ordinal"), stringIDToTypeID("targetEnum"));
if (!executeActionGet(r).hasKey(stringIDToTypeID("selection"))) { r_idx.putIndex(stringIDToTypeID("layer"), i); do_it = true; }
}
app.activeDocument.selection.deselect();
if (do_it)
{
var d = new ActionDescriptor();
d.putReference(stringIDToTypeID("null"), r_idx);
executeAction(stringIDToTypeID("delete"), d, DialogModes.NO);
}
alert("done");