Intercept document on save or close to execute JPG export process

I’m attempting to output a JPG preview of the InDesign page when the user either saves or closes the document. However, there appears to be no event fired when the document is saved, so I am trying to use just the close event for the document

Basic approach is to listen for the beforeClose event, cancel the close process, run the export script, then close the document via script. But it seems like the event fires, and while I am catching it, InDesign continues on it’s merry way and closes the document on me, before I can get the export process to execute.

let docBeforeCloseEventListener = app.addEventListener("beforeClose", handleBeforeCloseEvent);

function handleBeforeCloseEvent(theEvent){
  console.log('Document before close event received');
  if (app.activeDocument) {
    console.log('Closing document is ' +;

The beforeClose event is apparently cancelable according to the doco here, but I don’t know how to cancel it - .preventDefault() looks to be the correct method, but I get the error “The requested action could not be completed because the object no longer exists.”

Anoyone managed to intercept the beforeClose and do anything useful to the document being closed?

1 Like

To handle events in InDesign’s UXP requires a more complex code as shown in the document.

But even leaving that aside, probably preventDefault will not work now. @Anoop Please deny if this opinion is wrong.

You can do it by executing ExtendScript via doScript.

const { app, ScriptLanguage } = require('indesign') ;

const code = `
//@targetengine 'sample_text'
var docBeforeCloseEventListener = app.addEventListener("beforeClose", handleBeforeCloseEvent) ;

function handleBeforeCloseEvent(theEvent) {
  theEvent.preventDefault() ;
  alert('Document before close event received') ;
  app.removeEventListener("beforeClose", handleBeforeCloseEvent) ;
}` ;

app.doScript(code, ScriptLanguage.JAVASCRIPT) ;

There are beforeSave and afterSave events…

1 Like