Execute javascript on browser refresh

Hey everyone,

So a common problem I seem to run into a lot is where I need to execute some javascript to make a persistent change to the client side html.

Executing javascript is simple with

JavaScript.getCurrent().execute("Some script which makes a modification to the DOM"); But on a page reload (with the @PreserveOnRefresh annotation), that script is never executed again.

Is there a simple way to be able to make the javascript persistent.

I’ve tried adding a tag into a CustomLayout and adding that layout.

Something like:

CustomLayout l = new CustomLayout(); l.setTemplateContents("<script type='text/javascript'>alert(1);</script>"); addComponent(l); But the script never executes. It must be the way it is added that it is never fired.

Is there a simple way, without creating a whole new component, that would achieve what I’m after?

I’m sure the CustomLayout trick used to work in Vaadin 6 :slight_smile:

CustomLayout has code especially written to exclude tags and i think that was already present in Vaadin 6. The only way to use JS in CustomLayouts is when it is in a component listener like …onclick = “alert(‘test’)”…

Going back to your actual question:
You might be able to achieve this when modifying the Vaadin html header and adding a script tag with your code in the bootstraplistener. There is an example here
https://vaadin.com/forum#!/thread/4924537/4939495
but you might find a better one somewhere else on the forum…maybe even in the book.

Oh, you are right about the custom layout. I checked a Vaadin 6 project I had laying around and I had written a simple component which just outputs the raw html you give to it.

Anyway, I wrote a simple component to achieve what I wanted. Actually an extension.

It is just something it seems Vaadin goes out of it’s way to avoid (like stripping script tags from custom layout and labels?). And I’ve never figured out why.