JavaScript: Using a script stand-alone and in a smart rule

Now that JavaScript scripts can be used in smart rules, here’s a short tip on how to write a script so that it works stand-alone and in a smart rule without any changes.

Edit: In the original version, the function at the top was named onperformsmartrule, which is wrong: the correct name is performsmartrule;

In the smart rule, it works on the records selected by the rule. Outside of it (i.e. when invoked in Script Editor, from the script menu or with osascript, it works on the records currently selected in DT.

EDIT: The original code would run performsmartrule twice if it were executed inside of DEVONthink. The below version fixes this by first checking if the anonymous function is executing inside of DEVONthink or not. Only in the latter case is it calling performsmartrule.

function performsmartrule(records) {
  const app = Application("DEVONthink 3");
  records.forEach(r => {
           /* relevant code goes here */
  } /* end forEach */
} /* end performsmartrule */

/* Define a self-executing anonymous function that will run whenever 
the script is executed _outside_ of a DEVONthink smart rule */

(() => {
if (currentAppID() === "DNtp") return;
const app = Application("DEVONthink 3");
performsmartrule(app.selectedRecords());
})()

function currentAppID() {
  const p = Application.currentApplication().properties();
  return Application(p.name).id();
}
7 Likes