I am faced with a situation where my application requires cleanup no matter how the user leaves the page. To achieve this, I am using JavaScript to detect when the user exits the page and display a popup warning them that the current process will be halted. This question specifically addresses the popup aspect, as I want to clarify its necessity.
When the user initiates the process by clicking a button, the following code is executed:
JavaScript.getCurrent().execute(
"var beforeCloseListener = function (e) { var e = e || window.event; var message = " + LEAVE_PAGE_MESSAGE + "; if(e) e.returnValue = message; return message; } " +
"window.addEventListener('beforeunload', beforeCloseListener);"
);
This code successfully triggers a popup when the user attempts to close the browser, as intended. The Chrome developer tools screenshot below demonstrates that I can locate the method.
Chrome Developer Tools javascript search 1st try
However, upon reopening the browser, navigating back to the page, and clicking the button again, the popup does not appear when trying to close the browser.
Although the code is being executed again, it seems that the JavaScript is not properly attached. When searching in Chrome developer tools, I am unable to locate the method.
Chrome Developer Tools javascript search 2nd try
Given my limited knowledge of both Vaadin and JavaScript, I may be overlooking something in their respective lifecycles. Therefore, I am wondering why the JavaScript fails to be integrated into my application the second time around, despite functioning correctly initially? I suspect there may be a Vaadin feature that I am unaware of.
Interestingly, the behavior persists regardless of whether or not I use the removeEventListener method. Similar to my related question, I suspect that my removeEventListener is not being triggered as expected.
It is worth noting that this issue occurs consistently across all browsers I have tested, including Firefox, Chrome, Safari, and Opera.