Home > front end >  BeforeLeaveObserver is not invoked after page reload in Vaadin
BeforeLeaveObserver is not invoked after page reload in Vaadin

Time:12-17

I have a problem: BeforeLeaveObserver is not invoked after ui.getPage().reload(); I need to reload view after the user change the application language, so this action is invoked after the user change and save. Then the view is translated to another language dynamically. After that another functionality which is using BeforeLeaveObserver is not invoked. Any ideas how to make observer work again? Or maybe there is another way which will work?

I was trying with LocaleChangeObserver a had a trouble to refresh layout and translate it - it's too complicated.

CodePudding user response:

You can only rely on BeforeLeaveObserver for situations when the user navigates from one view to another in the same UI. Reloading the page causes a new UI to be created which means that BeforeLeaveObserver isn't triggered. The old UI instance is still there with the old view active.

The framework could in theory detect the situation specifically for a reload that is triggered from code but it's not trivially detectable when the user reloads through the web browser. It would be just as confusing if different types of reloading would lead to different outcomes.

For you case, you might want to instead redirect the user to a URL that contains a parameter that you can use to identify the custom configuration that the new UI is supposed to adopt.

CodePudding user response:

If you are experiencing issues with the BeforeLeaveObserver not being invoked after calling ui.getPage().reload(), it is likely because the reload is causing the view to be removed from the UI and replaced with a new instance.

One solution to this problem might be to register the BeforeLeaveObserver on the new view instance after the reload. You can do this by calling the addBeforeLeaveListener() method on the new view, passing in an implementation of the BeforeLeaveObserver interface.

Alternatively, you could try using the Page.BrowserWindowResizeEvent or the Page.BrowserWindowBlurEvent to trigger the reload, as these events should not cause the view to be removed from the UI.

ui.getPage().addBrowserWindowResizeListener(event -> ui.getPage().reload());
ui.getPage().addBrowserWindowBlurListener(event -> ui.getPage().reload());

Hope this helps!!

  • Related