The following script leverages the fit layers on screen command, offering a single history state.
/*
Zoom to Selection Bounds.jsx
v1.0, 1st April 2024, Stephen Marsh
https://community.adobe.com/t5/photoshop-ecosystem-discussions/fit-selection-to-screen-or-zoom-to-selection/td-p/14526195
*/
app.activeDocument.suspendHistory("Zoom to Selection", "main()");
function main() {
var selectionBounds = null;
try {
selectionBounds = app.activeDocument.selection.bounds;
if (selectionBounds) {
executeAction(stringIDToTypeID("copyMerged"), undefined, DialogModes.NO);
pasteInPlace();
reselect();
fitLayersOnScreen();
app.activeDocument.activeLayer.remove();
} else {
// There should be a selection active to zoom to the selection!
}
} catch (e) {
alert("Error!" + "\r" + e + ' on line: ' + e.line);
}
}
function pasteInPlace() {
function s2t(s) {
return app.stringIDToTypeID(s);
}
var descriptor = new ActionDescriptor();
descriptor.putBoolean(s2t("inPlace"), true);
descriptor.putEnumerated(s2t("antiAlias"), s2t("antiAliasType"), s2t("antiAliasNone"));
descriptor.putClass(s2t("as"), s2t("pixel"));
executeAction(s2t("paste"), descriptor, DialogModes.NO);
}
function fitLayersOnScreen() {
function s2t(s) {
return app.stringIDToTypeID(s);
}
var descriptor = new ActionDescriptor();
var reference = new ActionReference();
reference.putEnumerated(s2t("menuItemClass"), s2t("menuItemType"), s2t("fitLayersOnScreen"));
descriptor.putReference(s2t("null"), reference);
executeAction(s2t("select"), descriptor, DialogModes.NO);
}
function reselect() {
function s2t(s) {
return app.stringIDToTypeID(s);
}
var descriptor = new ActionDescriptor();
var reference = new ActionReference();
reference.putProperty( s2t( "channel" ), s2t( "selection" ));
descriptor.putReference( s2t( "null" ), reference );
descriptor.putEnumerated( s2t( "to" ), s2t( "ordinal" ), s2t( "previous" ));
executeAction( s2t( "set" ), descriptor, DialogModes.NO );
}
https://prepression.blogspot.com/2017/11/downloading-and-installing-adobe-scripts.html