@dublove this is one way to do it:
/**
* Example of starting a script by getting the
* selected stories or the whole document, but first
* confirming whether to process the whole document.
* @author m1b
* @version 2025-03-25
* @discussion https://community.adobe.com/t5/indesign-discussions/is-it-possible-to-automatically-determine-my-current-target-selection-using-only-one-variable/m-p/15227968
*/
(function () {
var targets = getStoriesOrDocument(app.activeDocument);
if ('Document' === targets.constructor.name) {
if (!confirm('Do you want to apply to whole document?'))
return;
// store document in an array for processing
targets = [targets];
}
// now do something with the stories or document
for (var i = 0; i < targets.length; i++) {
var target = targets[i];
$.writeln(target.constructor.name + ' ' + target.id);
}
})();
/**
* Returns the document's selected
* stories or the document itself.
* @author m1b
* @version 2025-03-25
* @param {Document} doc - an Indesign Document.
* @returns {Array<Story>|Document}
*/
function getStoriesOrDocument(doc) {
var stories = [],
unique = {},
items = doc.selection;
if (0 === items.length)
return doc;
for (var i = 0; i < items.length; i++) {
if (items[i].hasOwnProperty('parentStory')) {
if (unique[items[i].parentStory.id])
// already collected this story
continue;
unique[items[i].parentStory.id] = true;
items[i] = items[i].parentStory;
}
if ('function' === typeof items[i].changeGrep)
stories.push(items[i]);
}
return stories;
};
Edit 2025-03-25: added support for other selections, eg. an InsertionPoint.