The Vaadin JavaScript popup feature functions correctly only on the initial use during each session

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.

Answer №1

Recently, I encountered a similar issue with Vaadin. After some trial and error, I found a solution that worked for me. By assigning a function to a variable and then passing it to another function, the issue was resolved. You can update your code following this example:

JavaScript.getCurrent().execute(
    "someGlobal = function beforeCloseListener(e) { var e = e || window.event; var message = " + LEAVE_PAGE_MESSAGE + "; if(e)       e.returnValue = message; return message; } " +
    "window.addEventListener('beforeunload', someGlobal);"
);

Answer №2

After some troubleshooting, I have finally resolved the issue I was facing. It turns out that trying to call Vaadin's JavaScript.execute() method asynchronously was causing the problem. By making sure the necessary methods were executed within a UI.getCurrent().access() block, I thought I had fixed the issue. However, this turned out not to be the case.

By moving the javascript.execute() calls out of the executor and onto the main thread, I have successfully resolved the issue. In my scenario, running JavaScript synchronously is acceptable, so this solution worked for me. I plan on exploring the UI.access() method further to understand if my initial expectation was correct and if not, finding a more suitable approach to running JavaScript asynchronously. If I come across any helpful insights, I will update my explanation with that information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to modify an element in an array within a state-managed object, the input field loses focus

In attempting to address my issue, I have crafted what I believe to be the most concise code example. The main goal is to display a table on the page populated with exercise data retrieved from a database. This data is then assigned to an array of objects ...

While Advanced REST Client successfully retrieves an infinite JSON file from the AngularJS REST service, Postman encounters an error with the code ERR_INCOMPLETE_CHUNKED_ENCODING

I've encountered a peculiar issue. When making a REST call in Angular (using an app built with Ionic v1) to a Java endpoint, something goes awry and Chrome throws the following error: https://i.sstatic.net/1sxp7.png The code of interest is this Angul ...

Error: JSONP Label Validation Failed

My JSON URL is: The above URL returns the following JSON: { token: "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72" } Edit: Changed it to {"token": "2cd3e37b-5d61-4070-96d5-3dfce0d0acd9%a00a5e34-b017-4899-8171-299781c48c72"} ...

Asynchronous function nested within a loop

Hello there! I am currently working on converting a SQLite database to NeDb using the following code snippet: const sqliteJSON = require('sqlite-json'); const Datastore = require('nedb') const exporter = sqliteJSON('etecsa.db&apo ...

Having trouble uploading a file with Parse.File in an express web application

Currently, I am developing an express web application with a Parse backend. To render webpages, I am utilizing .ejs files. Upon clicking the submit button on the file upload form, Express routes me to testfile.js where I am using the Parse.File method to u ...

Tips on managing Array indexes in AngularJS

Just diving into the world of Angularjs and I have some JSON files containing an array of car objects that I'm displaying on my webpage. My goal is to have a "button" that, when clicked, will alert me with data specific to that particular button. The ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

JavaScript to enable button functionality for selected items

Currently, I am developing a To-Do List application. Once users input information, it gets displayed in a table format. My objective is to have the ability to select specific items from this table and apply various button functionalities to them such as ma ...

Guide on updating location and reloading page in AngularJS

I have a special function: $scope.insert = function(){ var info = { 'username' : $scope.username, 'password' : $scope.password, 'full_name' : $scope.full_name } $http({ method: &ap ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

Transmitting checkbox selections using Ajax

Here is the original code that I have written. It attempts to post the value of an input for each checked checkbox. <tbody class="myFormSaldo"> <tr> <td> <input name="checkbox['.$i.']" type="chec ...

Maximizing page space with ReactJS and advanced CSS techniques

I'm currently in the process of learning CSS and struggling a bit with it. My main issue right now is trying to make my react components fill the entire height of the browser window. I've been using Display: 'grid' and gridTemplateRows: ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Is the this.props.onChange method called within the render function?

I'm having trouble grasping the concept of the assigned onChange property in this TextField component I found in the material-ui library: <TextField style = {{"padding":"10px","width":"100%"}} type = {'number'} valu ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...

Issue with Swiper JS: The buttons on pages three and beyond are unresponsive

I'm having trouble with the functionality of the "Back" button on pages 2 and 3 of my website. Can anyone help me figure out why it's not working? My goal is to create a website that resembles a game menu, similar to Deus Ex The Fall. I'm u ...

Reset the input field upon button press

Is there a way to clear the input field after pressing the button? <div class="form-group autocomplete"> <div class="input-group search"> <input id="search" name="searchterm" type="search" class="form-control form-control search-input" pl ...

Tips for finding the position of a specific object within an array of objects using JavaScript when it is an exact match

I am working with an array of objects and need to find the index of a specific object within the array when there is a match. Here is an example of my current array: let x = [ {name: "emily", info: { id: 123, gender: "female", age: 25}}, {name: "maggie", ...

Having trouble receiving a response from axios

My goal is to use axios to submit a blog post and display a response message. If the response is "success," the process should proceed. For testing purposes, I am only using console.log("success ok"). However, I encountered a puzzling issue that I cannot f ...