Handling Session Ending in PJS Modules
The pjs.session.onEnd
function can be defined in any PJS Rich Display File (RDF) module and allows users to execute custom code when a RDF session is ended. This function is useful in situations where you need to perform cleanup operations, log data, or trigger any specific actions after the session ends, including unexpectedly by the user’s closing the browser or navigating away from the page.
Parameters: none
Returned value: unhandled
Asynchronous: yes. Calling function uses “await”.
First available in PJS version: 7.14.0
Example
This example shows how the pjs.session.onEnd
hook can be used to clean up resources when the browser is closed.
const { spawn } = require("child_process");
const childProcesses = [];
function main() {
pjs.defineDisplay("display", "pjs-1118-ws.json");
const fields = { exit: false };
pjs.session.onEnd = onEnd;
while (!fields.exit) {
display.screen.execute(fields);
if (fields.spawn) {
// Each time the user clicks on the "Spawn Child" button, run a script, which
// simply prints something to the console periodically.
const cp = spawn("node", ["modules/some-workspace/interval.js"], { stdio: "inherit" });
childProcesses.push(cp);
}
}
flags.LR = true;
}
// End all spawned child processes when the session ends, either by the program
// exiting, by the user navigating away from the page, by the debugger ending the session, etc.
function onEnd() {
while (childProcesses.length > 0) {
const childProcess = childProcesses[0];
if (childProcess) {
childProcess.kill("SIGKILL");
}
childProcesses.shift();
}
}