skip to Main Content

In order to improve SEO of my Vaadin application I’d like to set up custom meta tags.

For this purpose I’d like to use IndexHtmlRequestListener:

serviceInitEvent.addIndexHtmlRequestListener(new IndexHtmlRequestListener() {

            @Override
            public void modifyIndexHtmlResponse(IndexHtmlResponse indexHtmlResponse) {

                Optional<UI> optionalUI = indexHtmlResponse.getUI();

                if (optionalUI.isPresent()) {
                    UI ui = optionalUI.get();
                    Document document = indexHtmlResponse.getDocument();

                    String title = ui.getInternals().getTitle();
                    if(StringUtils.isNoneBlank(title)) {
                        setMetaTag(document, "og:title", title);
                    }

                    setMetaTag(document, "description", ...
                    setMetaTag(document, "og:image", ...
                }
            }

        });

}

As you may see, right now I’m able to get the title provided in the every single view via HasDynamicTitle interface. I’d like to follow the same schema for the rest of meta tags. Simply speaking – I want to define such set of tags in the every view and then be able to retrieve somehow such tags in modifyIndexHtmlResponse method and set up these values to the document meta tags.

Please advice how to access the current View instance from the modifyIndexHtmlResponse method.

2

Answers


  1. The IndexHtmlRequestListener is invoked when the application is bootstrapped during the very first request to the server; you shouldn’t assume a View exists at this stage. What you can do is access the VaadinRequest from the IndexHtmlResponse object, and that will give you the request path via getPathInfo. You should be able to deduce the headers you want to add based on that.

    Login or Signup to reply.
  2. Assuming you have a fully initialized UI instance, you can find the current view (along with any wrapping router layouts) from the list in ui.getInternals().getActiveRouterTargetsChain().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search