简体   繁体   English

网络套接字。 获取与现有的连接

[英]WebSocket. Get connection to existing one

Im doing a script for a 3D chat which is using websockets.我正在为使用 websockets 的 3D 聊天编写脚本。 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.我可以在 chrome 开发人员工具上看到,当有一个新的小时时,我会收到来自 websocket 的消息。

I wanna do this in javascript so i load an javascript along with when i load the site.我想在 javascript 中执行此操作,因此我在加载站点时加载了 javascript。 So how do i get already existing connection to websockets?那么我如何获得与 websockets 的现有连接?

You can see on this image, that it provide a websocket你可以在这张图片上看到,它提供了一个 websocket 在此处输入图片说明

How can i get my javascript loaded along with the site to get that connection and not a new one?如何让我的 javascript 与网站一起加载以获得该连接而不是新连接?

A webSocket connection is stored in a Javascript variable when it is created by the code that creates it.当创建它的代码创建 webSocket 连接时,它会存储在 Javascript 变量中。 You need access to that variable in the script that creates the webSocket connection.您需要在创建 webSocket 连接的脚本中访问该变量。 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.您可以检查创建 webSocket 连接的脚本并查看它存储 webSocket 对象的位置,以便查看是否可以访问该变量。

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).您的 Javascript 可以通过书签或浏览器扩展程序添加到页面中,或者显然是通过编辑网页的原始来源(尽管我认为在这种情况下您不能这样做)。

I needed to access a WebSocket created by an external library, so I didn't have the actual variable used to create it.我需要访问由外部库创建的 WebSocket,因此我没有用于创建它的实际变量。 Fortunately when WebSockets update, they trigger a message event on window , which you can easily hook into:幸运的是,当 WebSockets 更新时,它们会在window上触发一个message事件,您可以轻松地将其挂接到:

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).由于可能有多个 WebSocket 打开,您需要比较 origin 属性(它将是套接字连接到的 URI 的域,没有路径)。 The data sent through the WebSocket will be in the data property of the event.通过 WebSocket 发送的数据将在事件的data属性中。 Something like this:像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM