Intercepting beforeClose event on document/window

Hi, I’d like to be able to intercept the beforeClose event when closing a document, so I can run some processing before the window actually closes.

From what I’ve read and tested, the beforeClose event is not cancellable on the document itself, but it should be cancellable on the window.

However, whatever I try, the window close event always appears as invalid.

Has anyone managed to make this work, or do you have an idea of how to properly intercept it?

Thanks!

Here’s a code snippet to illustrate this point.

const { app } = require("indesign");

function addListenerToWindow(myEvent) {
    const doc = myEvent.target;
    for (let index = 0; index < app.windows.count(); index++) {
        const window = app.windows.item(index);
        if (window.parent.id === doc.id) {
            window.addEventListener("beforeClose", beforeCloseWindow)
        }
    }
}

function beforeCloseWindow(evt) {
    console.log(evt) // => Event {isValid: false, constructorName: ""}
    console.log("beforeCloseWindow");
}

app.addEventListener("afterNew", addListenerToWindow);