The problem is the “beforeUnloadHandler” variable isn’t available in the scope of the 2nd run JavaScript action.
You can make the object globally available by appending it to the window object.
For example
window.beforeUnloadHandler = (event) => {
event.preventDefault();
event.returnValue = true;
};
window.addEventListener("beforeunload", window.beforeUnloadHandler);
And then when removing it, the object will be accessible in the window object.
window.removeEventListener("beforeunload", window.beforeUnloadHandler);