Vaadin 14 execute js failed to execute the JavaScript function with elements as argument

79 views Asked by At

I'm working on the vaadin14.10.5 on the client-side WebSocket implementation, so I wrote the js file as below to call the server-side code from the Javascript.

let socket;
var connected = false;
window.connectWebsocket =  function (url, **ele**) {
    if(!connected){
        socket = new WebSocket(url);
    }
    console.log('Element : ' + ele);
    socket.addEventListener('open', (event) => {
    console.log('WebSocket connection opened:', event);
    // You can send data to the server using socket.send()
    socket.send('{"key": "Hello server!!!"}');
    connected = true;
    // this.$server.onOpen();
    console.log('calling server method....');
    console.log(window.Vaadin.Flow.clients);
  **  ele.$server.onOpen();**
 });

 // Event handler for when a message is received from the server
 socket.addEventListener('message', (event) => {
   console.log('Message received from server:', event.data);
   // You can handle the incoming data here
   if(ele)
    ele.$server.onMessage(event.data);
 });

 // Event handler for when the connection is closed
 socket.addEventListener('close', (event) => {
   console.log('WebSocket connection closed:', event);
   if(ele)
    ele.$server.onClose(event.code, event.reason, event.wasclean);
   connected = false;
 });

 // Event handler for any errors that occur
 socket.addEventListener('error', (event) => {
   console.error('WebSocket error:', event);
   if(ele)
    ele.$server.onError();
 });

 return 1;
}

WebScoktClient.java:

@JavaScript("./websocket-client.js")
@Tag("tmff-websocket")
public class WebsocketC extends Div {

    @ClientCallable
    protected void onOpen() {
        System.err.println("Connection opened...");
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);
        System.out.println("@@@@" + this.getElement());
        UI.getCurrent().getPage().executeJs("connectWebsocket($0,$1)", url, ws.getElement()); // not wokring
        UI.getCurrent().getPage().executeJs("alert($0)", this.getElement()); // not working
    }
}

Getting the error: $server undefined If I pass the argument other than element it is working fine.

Need to call the server-side method from the javascript for my custom component.

0

There are 0 answers