How can you use JavaScript and Pega APIs to automatically release a lock when the user closes the browser, logs off, or clicks the back button?

Share with Love

Thanks for the context! In Pega, lock management is crucial to avoid stale locks that prevent others from accessing work objects like cases (e.g., train/track in your scenario). Since Pega typically handles locks on the server side, using JavaScript to handle lock release must be carefully integrated with server-side APIs.

Your goal is to release the lock when the user closes the browser, logs off, or clicks the back button. Here’s how you can approach this using JavaScript and Pega APIs:

✅ 1. Use window.onbeforeunload to detect browser/tab close or navigation

window.onbeforeunload = function (e) {
// Call custom function to release the lock
releaseLock();
};

✅ 2. Optional: Use popstate or hashchange for back/forward navigation

If you’re using browser history or hash-based routing:

window.onpopstate = function (event) {
releaseLock();
};
window.onhashchange = function () {
releaseLock();
};

✅ 3. Release Lock with Pega AJAX Call

You need to call a Pega activity or data page that releases the lock. Here’s a sample function using SafeURL to call a custom activity (ReleaseTrainLock):

function releaseLock() {
try {
// Create a SafeURL object pointing to your custom activity
var safeURL = new SafeURL(“MyApp-Work-Train”, “ReleaseTrainLock”);

// Make an asynchronous call to the activity
pega.u.d.asyncRequest(“GET”, safeURL.toURL(), {
success: function(response) {
console.log(“Lock released successfully”);
},
failure: function(error) {
console.error(“Failed to release lock”, error);
}
});
} catch (e) {
console.error(“Error in releaseLock(): “, e);
}
}

Note: Replace MyApp-Work-Train and ReleaseTrainLock with your actual class and activity.

✅ 4. Server-Side: Create ReleaseTrainLock Activity

This activity should:

  • Use Obj-Open-By-Handle or Obj-Open

  • Use Page-Remove or Unlock method

  • Ensure it doesn’t fail silently — return status to JS

🔒 Caution:

  • onbeforeunload can be unreliable in some browsers for sending async requests. For better guarantee, use navigator.sendBeacon:

function releaseLock() {
var data = new Blob([], { type: 'application/json' });
navigator.sendBeacon("/prweb/PRServlet?Activity=MyApp-Work-Train.ReleaseTrainLock", data);
}

✅ 5. Tie-In With Pega Logoff

In your logoff or timeout handler, ensure releaseLock() is called before ending the session.