First, we need to find a container for the sample code. By convention, we will use the Script Label panel (Window > Automation > Script Label). This mysterious receptacle allows the user to attach an arbitrary label (string) to the selected page item (TextFrame, Polygon, etc.). What for? Only for scripting purposes. In most cases, the label property is used to identify or ‘tattoo’ the layout components involved in a script process, but we will use it to encapsulate the instructions that need to be interpreted.

Keep in mind that the Script Label data are connected to the page item that is currently selected. Consequently, you must have or create a temporary object to that end (in your InDesign document).

Now we want to handle our special label from the outside and to process it like a real script. The Application doScript method provides a friendly way to do that. Let us create a meta-script, RunLabel.js, containing the following code:

Application.prototype.main = function()
//--------------------------------------
// Run as script the label (string) of the selected object
// !! If you change the label, you need to unfocus
// !! the "Script Label" panel to update the value
{
try
    {
    if ( this.selection.length <= 0 )
        {
        throw new Error("No selection!");
        }
    var snippet = this.selection[0].label;
    this.doScript(snippet, ScriptLanguage.javascript,
        undefined, UndoModes.entireScript, "RunLabel");
    }
catch(ex)
    {
    alert(ex);
    }
}
app.main();
 

To install and test this solution, save RunLabel.js in your scripts folder. That's all! The meta-script will send to the JS interpretor any code written in the label panel (from the selected page item). Note that the UndoModes.entireScript option makes the whole code undo-able.

RunLabel Demo

RunLabel Demo