Search code examples
javascriptvaadinvaadin8

What is the Vaadin 8 way of adding code to the html head tag?


Other SO answers suggest overriding ApplicationServlet.writeAjaxPageHtmlHeader, but I cannot find those classes and methods in Vaadin 8.

I cannot find anything similar in com.vaadin.server.VaadinServlet or com.vaadin.ui.UI.

There is the @JavaScript annotation, but if I put that on my UI class, the script would be loaded for every page of my application. I need it only on one specific page.


Solution

  • The initial HTML page is called bootstrap page in Vaadin. There is some documentation that hints you to right direction in Book of Vaadin.

    In Vaadin 8, you need to add BootstrapListener to session. You can get created sessions by adding SessionInitListener in VaadinServlet.

    Register Session

    This example is using Vaadin with Spring Boot but the same principle applies when not using Spring Boot.

    @Component("vaadinServlet")
    @WebServlet(urlPatterns = "/*", name = "BootstrapVaadinServlet", asyncSupported = true)
    @VaadinServletConfiguration(ui = BoostrapUi.class, productionMode = false)
    public class BootstrapVaadinServlet extends SpringVaadinServlet {
        private static final Logger logger = LoggerFactory.getLogger(BootstrapVaadinServlet.class);
        @Override
        protected void servletInitialized() throws ServletException {
            super.servletInitialized();
            getService().addSessionInitListener(this::addBoostrapListenerOnSessionInit);
        }
    
        private void addBoostrapListenerOnSessionInit(SessionInitEvent sessionInitEvent) {
            sessionInitEvent.getSession().addBootstrapListener(new AppBootstrapListener());
        }
    }
    

    Implement html head tag modification

    public class AppBootstrapListener implements BootstrapListener {
        @Override
        public void modifyBootstrapFragment(BootstrapFragmentResponse bootstrapFragmentResponse) {
    
        }
    
        @Override
        public void modifyBootstrapPage(BootstrapPageResponse res) {
            Elements headTags = res.getDocument().getElementsByTag("head");
            Element head = headTags.get(0);
            head.appendChild(metaExample(res.getDocument()));
        }
    
        private Node metaExample(Document document) {
            Element meta = document.createElement("meta");
            meta.attr("author", "Me");
            return meta;
        }
    }