Does anybody know whether there is one listener for the browser tab changes

There are many tabs of the Chrome browser opened in the runtime when navigate to a new view. what I want to do is reload the data when the tab selection is changed.

But after go through the code, I didn’t find a way to implement this. I don’t know how to add the listener when the tab of the Chrome selection chanages.
For the JavaScript, we may do like this:

document.addEventListener(‘visibilitychange’, function() {
if (document.visibilityState === ‘hidden’) {
console.log(“leave tab”);
} else {
console.log(“enter tab”);
}
});

but how to let server know in Vaadin.

Hey Yuri,

Not an expert here, but maybe this helps:

Hi Yuri

it appears you found a way to add a JS listener that gets triggered when the user manually enters or leaves the browser-tab, but you only need a way to let actual java/vaadin view know about it.
This is where [@ClientCallable]
(https://vaadin.com/docs/v14/flow/element-api/client-server-rpc.html#clientcallable-annotation) annotation comes into play.

Here is how your view could look like (tested, works):

@Route("test")
public class MyView extends VerticalLayout {
    public MyView () {
	    addAttachListener(attachEvent -> {
            attachEvent.getUI().getPage().executeJs(
			    "document.addEventListener('visibilitychange', function() {$0.$server.logVisibilityChange(document.visibilityState);});",
				this.getElement());
        });
	}

    @ClientCallable
    public void logVisibilityChange(String visibilityState) {
	    if("hidden".equals(visibilityState)) {
			LOGGER.debug("leave tab");
		} else {
			LOGGER.debug("enter tab");
		}
    }
}

Luis Gutierrez:
Hey Yuri,

Not an expert here, but maybe this helps:

Thanks for your reply.

I am sorry I was using Vaadin 8.So this maybe does’t work for me.

Kaspar Scherrer:
Hi Yuri

it appears you found a way to add a JS listener that gets triggered when the user manually enters or leaves the browser-tab, but you only need a way to let actual java/vaadin view know about it.
This is where [@ClientCallable]
(https://vaadin.com/docs/v14/flow/element-api/client-server-rpc.html#clientcallable-annotation) annotation comes into play.

Here is how your view could look like (tested, works):

@Route("test")
public class MyView extends VerticalLayout {
    public MyView () {
	    addAttachListener(attachEvent -> {
            attachEvent.getUI().getPage().executeJs(
			    "document.addEventListener('visibilitychange', function() {$0.$server.logVisibilityChange(document.visibilityState);});",
				this.getElement());
        });
	}

    @ClientCallable
    public void logVisibilityChange(String visibilityState) {
	    if("hidden".equals(visibilityState)) {
			LOGGER.debug("leave tab");
		} else {
			LOGGER.debug("enter tab");
		}
    }
}

Thanks for your reply.

I am sorry I was using Vaadin 8.So this maybe does’t work for me.