Javascript form Vaadin (almost) working


Want to call js code from within flow.
When doing this:

getElement().executeJs("function greet(name) { console.log('hello ' + name);}; greet('Main');");

it works perfectly - I get the console log message.

However, putting the js code in a js-file and importing it with

@JavaScript(value = "frontend://script.js")

and just calling


I get: ReferenceError) : greet is not defined

Everything is done from the MainView constructor as the only thing going on in the program.

I guess it has to do with the “scope” of the js-code, being one and the same when everything is in the same executeJs statement, but missing when trying to call it in a .js file.

I am absolutely sure that the file gets icluded, as if I call the greet() function directly from within it, I get the log when running the Vaadin program:

function greet(name) { console.log("howdy " + name); }

Any help?


In your JS file, use window.greet = function(name) { ... }

JS scripts that are imported using annotations on components/views are scoped to the element of the annotated component. JS executed with getElement().executeJs(...) is executed on global/window scope and can’t see the greet function. Therefore, you should define the greet function on the window just like Olli suggested. Then it will find the greet function.

… that did the trick!