0

In my Vaadin 12 project:

import com.vaadin.flow.component.dependency.HtmlImport
import com.vaadin.flow.component.dependency.JavaScript
import com.vaadin.flow.component.dependency.StyleSheet
import com.vaadin.flow.component.html.Div
import com.vaadin.flow.component.page.BodySize
import com.vaadin.flow.component.page.Page
import com.vaadin.flow.router.Route
import com.vaadin.flow.server.VaadinRequest
import org.slf4j.LoggerFactory

@Route(value = "myform")
@JavaScript("https://somejavascript.js")
class MyForm : Div() {
    private val logger = LoggerFactory.getLogger(this::class.java)

    init {
        val request = VaadinRequest.getCurrent()
        val myparam= request.getParameter("myparam")
        logger.info("myparam = $myparam")

    }
}

As you can see I import script: somejavascript.js by annotation. Nice. This script has method : myJavaScriptMethod How I can call this method in my Vaadin class MyForm ?

Alexei
  • 14,350
  • 37
  • 121
  • 240

1 Answers1

1

You can call your JS function myJavaScriptMethod() with this code:

UI.getCurrent().getPage().executeJavaScript("myJavaScriptMethod();");

You can find the documentation here
(strangely this documentation is only shown for the vaadin version 11, but it's still done the same way in Vaadin 12 and 13)

kscherrer
  • 5,486
  • 2
  • 19
  • 59
  • How I can pass one String param to this method? – Alexei Apr 02 '19 at 14:03
  • based on the linked documentation, you can do this with `UI.getCurrent().getPage().executeJavaScript("myJavaScriptMethod($0);", myStringVariable);` – kscherrer Apr 02 '19 at 14:09
  • I try this: UI.getCurrent().getPage().executeJavaScript("myJavaScriptMethod($0);", myParam); - but I get error: (ReferenceError): myJavaScriptMethod is not defined – Alexei Apr 02 '19 at 14:10
  • Then your javascript import did not work. I'm not sure if providing external js files work in the @JavaScript annotation. Can you download said js script and put it into your static resources folder? – kscherrer Apr 02 '19 at 14:13
  • Can you confirm that when you enter *the very same URL to the js file* into the browser, you get a js file (AKA is your url a valid url to a js script)? – kscherrer Apr 02 '19 at 14:34
  • 1
    The [API](https://vaadin.com/api/platform/13.0.3/com/vaadin/flow/component/dependency/JavaScript.html#value--) of the `@JavaScript` annotation states that absolute URL do work. – kscherrer Apr 02 '19 at 14:41
  • based on your new question, it seems you were able to make it work? Can you please share what it was? thanks – kscherrer Apr 02 '19 at 15:20
  • Now I get another errror: https://stackoverflow.com/questions/55478212/vaadin-12-javascript-java-lang-illegalargumentexception-cant-encode-class-ja – Alexei Apr 02 '19 at 15:21
  • I know thats what I meant. it implies that you do no longer get this error described here. How did you make it work? was the url to your js wrong or was it something else? – kscherrer Apr 02 '19 at 15:24