Kevin Steen Hansen
Kevin Steen Hansen

Reputation: 555

WebSocket. Get connection to existing one

Im doing a script for a 3D chat which is using websockets. Every hour you get on the chat, then you have to click "OK" to get the hour in your profile. So i want to make a script that can detect when the box is there to click okay. I can see on the chrome developer tool, that i reviece a message from the websocket when there is a new hour.

I wanna do this in javascript so i load an javascript along with when i load the site. So how do i get already existing connection to websockets?

You can see on this image, that it provide a websocket enter image description here

How can i get my javascript loaded along with the site to get that connection and not a new one?

Upvotes: 2

Views: 5420

Answers (2)

Mike
Mike

Reputation: 24393

I needed to access a WebSocket created by an external library, so I didn't have the actual variable used to create it. Fortunately when WebSockets update, they trigger a message event on window, which you can easily hook into:

window.addEventListener('message', messageEventListener, false);

Since there could be more than one WebSocket open, you need to compare the origin property (which will be the domain of the URI the socket connects to without the path). The data sent through the WebSocket will be in the data property of the event. Something like this:

const messageEventListener = (e) => {
  if (e.origin === 'https://paygatewaway.example'
    && e.data.status 
    && e.data.status === 'paid'
  ) {
    // Handle change
  }
};

Upvotes: 0

jfriend00
jfriend00

Reputation: 708026

A webSocket connection is stored in a Javascript variable when it is created by the code that creates it. You need access to that variable in the script that creates the webSocket connection. There's no other way to get it.

You can examine the script that creates the webSocket connection and see where it is storing the webSocket object so see if you can to that variable.

Your Javascript can be added to the page via a bookmarklet or a via a browser extension or obviously by editing the original source of the web page (though I assume you can't do that in this case).

Upvotes: 6

Related Questions