Redirect to external URL using BeforeEnterObserver

HI all,

I want to redirect to a external page using the BeforeEnterObserver interface

this is my code

@Route(value = "hello", layout = MainView.class)
@PageTitle("Shortener")
@CssImport("./styles/views/helloworld/hello-world-view.css")
@RouteAlias(value = "", layout = MainView.class)
public class HelloWorldView extends Div implements BeforeEnterObserver{

    private TextField name;
    private H1 mainTitle;
    private String parameter = "";

    public HelloWorldView() {
        setId("hello-world-view");
        
        //some code here
        
    }

	@Override
	public void beforeEnter(BeforeEnterEvent event) {
		
		getUI().get().getPage()
			   .executeJavaScript("window.location.href = 'https://www.google.com/'");
		
	}


}

And i getting this error message

java.util.NoSuchElementException: No value present
	at java.base/java.util.Optional.get(Optional.java:141) ~[na:na]

	at com.example.application.views.helloworld.HelloWorldView.beforeEnter(HelloWorldView.java:70) ~[classes/:na]

	at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.sendBeforeEnterEvent(AbstractNavigationStateRenderer.java:606) ~[flow-server-4.0.4.jar:4.0.4]

Seems getUI method return a null object, is there a way to redirect to external website without use getUI method?

You are calling getUI().get() in beforeEnter so I think there is no UI yet.
Have a look at

https://vaadin.com/api/platform/14.4.2/com/vaadin/flow/router/BeforeEvent.html#forwardTo-java.lang.String-

INPUTsys Chris Peter:
You are calling getUI().get() in beforeEnter so I think there is no UI yet.
Have a look at

https://vaadin.com/api/platform/14.4.2/com/vaadin/flow/router/BeforeEvent.html#forwardTo-java.lang.String-

Thanks for your reply but i think forward method only works with internal views and it is not possible redirect to external URLs

The BeforeEnterEvent event object contains a reference to the UI. You could have something like

   event.getUI().getPage().open(someUrl, "_self");

Note that this will not prevent the view itself from being opened briefly - if you need to stop that from happening, you should reroute to a special route where the Page.open occurs.

HI @Olli Tietäväinen,

i have tried your code and worked but i want to avoid redirect the flow to another Vaadin view and go directly to my custom URL in this case www.google.com, not sure if it approach is possible or not, maybe some workaround using servlets or the VaadinServiceInitListener.

Any advice is welcome :slight_smile:

Thanks
Rene Garnica

Why do you want to avoid the redirect? The URL in the browser bar will stay the same if you use event.rerouteTo(). Another alternative would be to use a BeforeLeaveObserver instead of BeforeEnterObserver. Consider also that you can have these event handlers on the main layout instead of the child routes.