Closing the GWT Java window: A step-by-step guide to logging out

After researching, I discovered that in order to Log Out of the application, one must close the window with the following code snippet:

If you are looking for a solution, you can find it in this answer: How to run JavaScript function from GWT Java with JSNI?

Specifically for Java:

myButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
closeWindow();
};
});

public static native void closeWindow() /*-{ $wnd.closeWindow();}-*/;

Then, in JavaScript within your application's .html page:

<script type="text/javascript" language="javascript">
function closeWindow() {
window.open('','_self','');
window.close();
</script>

Incorporating this into my application:

    //Log Out Button
    Button logOutButton = new Button("Log Out");
    logOutButton.addClickHandler(new ClickHandler(){
        public void onClick(ClickEvent event) {
        closeWindow();
        }
    });

    public static native void closeWindow() /*-{ $wnd.closeWindow();}-*/;

And the accompanying HTML:

<!doctype html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">

        <title>Wrapper HTML for AwardTracker</title;

        <script src="org.AwardTracker.AwardTracker/org.AwardTracker.AwardTracker.nocache.js">
            <type="text/javascript">
            function closeWindow() {
                window.open('','_self','');
                window.close();
            }
        </script>

    </head>

    <body>

        <iframe id="__gwt_historyFrame" style="width:0;height:0;border:0"></iframe>

    </body>

</html>

Despite implementing this code, I encountered an error on the lines:

closeWindow(); 

Saying, "The method closeWindow() is undefined for the type new ClickHandler(){}"

public static native void closeWindow() /*-{ $wnd.closeWindow();}-*/;

This issue has multiple markers which need to be addressed. Furthermore, I received valuable feedback on using sessions (via RemoteServiceServlet) in my application. Therefore, based on the suggestions provided, I attempted the following:

On the client side:

        logOutButton.addClickHandler(new ClickHandler(){
            public void onClick(ClickEvent event) {
            //Invalidate the session and then reload the application.
            AsyncCallback<Void> callback = new InvalidateSessionHandler<Void>(SelectPersonView.this);
            rpc.invalidateSession(callback);
            }
        });

class InvalidateSessionHandler<T> implements AsyncCallback<Void> {
    SelectPersonView view;

    public InvalidateSessionHandler(SelectPersonView view) {
        this.view = view;
    }

    public void onFailure(Throwable ex) {
        System.out.println("RPC call failed - InvalidateSessionHandler - Notify Administrator.");
        Window.alert("Connection failed - please retry.");
    }

    public void onSuccess(Void result) {
        //Reload the application.
        Window.Location.assign("/");    
    }
}

On the server side:

public void invalidateSession() {
    getThreadLocalRequest().getSession().invalidate(); // kill session 
}

Although this implementation seems to be effective, I am struggling to test multiple sessions locally without a test server for deployment. I humbly request assistance from someone experienced in this area to validate my approach and ensure it does not introduce any production issues. My main concern is inadvertently logging out all users, especially after encountering a data visibility issue due to unsegregated sessions in the past. This issue has been resolved, and I am keen to avoid any regression in this fix!

Answer №1

  1. It is not possible to use JavaScript to close a window that was opened by a user. JavaScript can only close windows that were opened by the application itself.

  2. Closing a window will not impact user authentication, as authentication systems typically rely on server sessions or cookies.

If your authentication system is session-based, when a user logs out, you must (1) invalidate the user's session, and (2) reload the application, which will show the default entry point for non-authenticated users (such as the home page or login page).

Answer №2

When it comes to closing a page with Javascript, it's important to note that the page can only be closed if it was opened by the same script. This means that the closeWindow() function won't work as expected. So, here are a few alternatives:

  1. If your application doesn't rely on sessions and simply needs to close the window, you can remove the iframe from the DOM instead of closing the entire page. This can be achieved using JavaScript:

document.getElementById('iframeid').innerHTML = '';

  1. On the other hand, if your application uses sessions (such as via RemoteServiceServlet), you will need to invalidate the session first before removing the element from the DOM. The exact method for this may vary.

Another option is to reload the iframe, which essentially refreshes your application:

document.getElementById('iframeid').src = document.getElementById('iframeid').src

Answer №3

Here is the final code that I implemented: I have integrated sessions using RemoteServiceServlet in my application. To properly handle this, I first invalidate the session and then remove the element from the dom. The following code snippet represents my final implementation:

On the client-side:

        logOutButton.addClickHandler(new ClickHandler(){
            public void onClick(ClickEvent event) {
                // Invalidate the session and reload the application.
                AsyncCallback<Void> callback = new InvalidateSessionHandler<Void>(SelectPersonView.this);
                rpc.invalidateSession(callback);
            }
        });

class InvalidateSessionHandler<T> implements AsyncCallback<Void> {
    SelectPersonView view;

    public InvalidateSessionHandler(SelectPersonView view) {
        this.view = view;
    }

    public void onFailure(Throwable ex) {
        System.out.println("RPC call failed - InvalidateSessionHandler - Notify Administrator.");
        Window.alert("Connection failed - please retry.");
    }

    public void onSuccess(Void result) {
        // Reload the application.
        Window.Location.assign("/");    
    }
}

On the server-side:

public void invalidateSession() {
    getThreadLocalRequest().getSession().invalidate(); // Terminate session 
}

Invoking getThreadLocalRequest().getSession().invalidate(); will redirect me to the login window, while Window.Location.assign("/"); will redirect me to the tomcat page. Feel free to choose whichever option suits your needs.

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

Using Angular directives to dynamically add event listeners with the ng-repeat directive

I am currently working with a directive that includes event listeners for an element in the link function. For example: ... link: function(scope, element) { // this gives us the native JS object var el = element[0]; el.draggable = true; ...

`What can be done if ng-if is not responding?`

I'm facing an issue where I want to display a link <a href> only when a certain condition is met, but the link doesn't show up as expected. I have already attempted to experiment with changing the position of the code (inside or outside of ...

Is there a way to alter the camera's focal point in THREEJS to focus on a specific object already in the scene?

Currently, I am working with a scene extracted from a THREEJS example (https://threejs.org/examples/webgl_loader_fbx.html) that involves importing and displaying a threejs.json scene. The rendering of the scene works perfectly; I have a grid in place with ...

Choosing a drop-down option from a list item

When trying to select an option from a dropdown menu, I encountered an error using the following code: Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

Discovering documents using the outcome of a function in mongoose

Hey there, I have a scenario with two schemas known as user and driver, both containing latitude and longitude attributes. My goal is to search the database for nearby drivers based on the user's current location (latitude and longitude) using a custo ...

Issue with executing Mongoose's .save() method

I am facing an issue with a piece of code that is not functioning as expected. My goal is to save a user document after modifying it with an ObjectId by adding it to an array. However, the user.save() function does not seem to execute, as the document rema ...

Import data from a distant file into a node Buffer within the web browser

Currently, I am utilizing browserify to utilize this particular package within the browser. Specifically, I have developed a phonegap application that retrieves .fsc files from the server. The code snippet looks like this: var reader = new FileReader( ...

Activating Bootstrap modal when a navigation link is clicked

Just started a site for a client and new to Bootstrap. I've got the layout down - full-width page with "Top Nav" within the nav bar, looking to create a modal effect drop-down. When clicking on "About", it should trigger the .modal function. However, ...

Confirm that images have been loaded correctly and are visible on the website by utilizing Selenium

In this validation scenario, when checking the website using URL response we receive a 200 OK response. However, there are cases where images on the website fail to load due to errors in CSS or JS files. I am seeking a solution to validate this specific s ...

Strange behavior in Vue observed. The v-if directive is not properly monitoring changes

I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initial ...

The ngBindHtml feature in AngularJS 1.2 does not handle processing of line breaks (/r & /n)

I have a string with a lot of extra whitespace, as it appears on my server: var care_description = "MATERIAL\r\n \r\n 56% Acrylic, 24% Rayon, 20% Polyester\r\n \r\n CARE\r\n \r\n Machine ...

The execution of my Nodejs API using the 'npm start' command is unsuccessful, resulting in the following error message

After cloning the project from GitLab, I proceeded to install node_modules using "npm install -g" and ran the "npm start" command in the terminal. However, I encountered errors as shown below: Error Cannot find module '../services/' Require ...

Accessing data from shared preferences with Gson

I'm facing an issue where, after saving my ArrayList into SharedPreferences using JSON and trying to load it back into my ListView, the ListView does not update. Despite reading numerous articles, I have not been able to find a solution that addresses ...

Experiencing difficulty in parsing the JSON document

I am struggling with reading a .JSON file (todo.json) in my Angular.Js project. The file is stored on the server, and all static files are saved within the 'public' folder of my basic Express server. Even though I can access the todo.json file di ...

Struggling to implement a JScrollPane on a JFrame

I need assistance with the code snippet provided below. The scroll pane is visible, but the sliders are not displaying. Even after resizing the frame, the sliders remain invisible. Can anyone offer some guidance? import javax.swing.*; public class sampl ...

Clicking our way back through the loop

Looking to display a name when each item is clicked. I've assigned an ID to each element, but it seems like I'm overlooking something. In the current code, I'm thinking there should be a variable involved, but I'm uncertain: $(document ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Is there a way for me to increment the value of 'sessionStorage.fgattempt' whenever either 'fgMade()' or 'threeMade()' are called?

Currently, I am developing a basketball game stat tracker and need to update the field goal attempts every time I make a field goal or three-pointer. Additionally, I am looking for ways to optimize the javascript code provided. The main requirement is to ...