This version will just flatten all open docs, without saving or closing (probably closer to what you were looking for than the previous script).
/*
Use this script at your own risk!
Flatten image for all open documents
https://community.adobe.com/t5/photoshop-ecosystem-discussions/flatten-image-for-all-open-documents/m-p/12617518#M610710
Flatten All Open Files.jsx
Stephen Marsh, v1.0 - 26 December 2021
*/
#target photoshop
// CHECK FOR OPEN DOCS
if (app.documents.length) {
// OPTIONAL CONFIRMATION
if (!confirm("Are you really sure that you wish to flatten all open docs?", false)) {
//throw alert("Script cancelled!");
throw null;
}
// SET THE CURRENT DOC AS ORIGINAL DOC
var actDoc = app.activeDocument;
// LOOP OVER OPEN FILES
for (var i = 0; i < app.documents.length; i++) {
app.activeDocument = app.documents[i];
app.activeDocument.flatten();
}
// RETURN TO THE ORIGINAL DOC
app.activeDocument = actDoc;
// END OF SCRIPT NOTIFICATION
app.beep();
alert("All open doc's layers have been flattened!")
// ALERT IF NO DOCS OPEN
} else {
alert('You must have a document open!');
}