user33054
user33054

Reputation: 91

javascript websocket onmessage event.data

Using JavaScript WebSocket how to pass event.data out onMessage function?

var eventData = EventRequest("text");


  ..... codes .....


EventRequest = function (text)
{
   var socket = new WebSocket ('ws://localhost:8080/');
   websocket.onopen = function(evt) { onOpen(evt); };
   websocket.onmessage = function(evt) { onMessage(evt); };

function onOpen (evt)
{
   socket.send("text");
}

function onMessage (evt)
{
   alert (evt.data);
   return evt.data;
}
};

I tried different ways to pass evt.data out, but I have not been able to. I can see the correct evt.data data. I just can not pass the data out of onMessage function.

I tried

function wcConnection (){
   this.dataInput = '';
}

Inside onMessage function, I added

function onMessage (evt)
{
   alert (evt.data);
   this.dataInput = evt.data;
}

Any help would be appreciated.

Upvotes: 9

Views: 52909

Answers (3)

Pranavjeet.Mishra
Pranavjeet.Mishra

Reputation: 154

Once you created an instance of your websocket using new , will be able to get message event OnMessage . If you using react then ,

    useEffect(() => {
    WebSocketScale.onmessage = (event: any) => {
        value.push(JSON.parse(event.data));
}, []);

Upvotes: 0

Mohit Satish Pawar
Mohit Satish Pawar

Reputation: 61

Why are you returning value to websocket.onmessage function? This is the function where you got that value. If you want to pass the value to another function just pass the event object to that function and access it using "evt.data".

websocket.onmessage = function(evt) { responseData(evt); };
function responseData(evt) {
    /* Here is your data, Do you what you want! */
    console.log(JSON.parse(evt.data));
}

Upvotes: 2

Terry
Terry

Reputation: 533

If you server is python tornado

def on_message(self, message):
        t = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        self.write_message(t)

In your client, to retrieve the message, you could do

ws.onmessage = function (evt) { 
    console.log(JSON.parse(event.data));
}

you should see the json in the console

Upvotes: 8

Related Questions