如何在 Phantom.js 中监控 WebSocket 通信? [英] How to monitor WebSocket communication in Phantom.js?

查看:19
本文介绍了如何在 Phantom.js 中监控 WebSocket 通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Phantom.js 文档展示了如何监控 HTTP 通信:http://phantomjs.org/network-monitoring.html

Phantom.js documentation shows how to monitor HTTP communication: http://phantomjs.org/network-monitoring.html

但是,它不适用于 WebSockets.如何在 Phantom.js 中监控 WebSocket 通信?

However, it does not work for WebSockets. How can I monitor WebSocket communication in Phantom.js?

推荐答案

PhantomJS 1.x 不支持 WebSockets1,因此您无法监控它们.如果页面使用 WebSockets 的一些后备,那么 page.onResourceRequestedpage.onResourceReceived 可用于记录消息的元数据.PhantomJS 不会以任何方式暴露实际发送的数据.

PhantomJS 1.x does not support WebSockets1, so you cannot monitor them. If the page uses some fallback for WebSockets, then the page.onResourceRequested and page.onResourceReceived can be used to log the meta data of the messages. PhantomJS does not expose the actual data sent in any way.

WebSockets 在 PhantomJS 2 中正常工作.由于不需要回退,不可能观察这些事件的流量.上面提到的事件处理程序不显示任何内容.查看消息的唯一方法是尽早代理 WebSocket 对象:

WebSockets work correctly in PhantomJS 2. Since no fallback is necessary, it is not possible to observe the traffic with those events. The event handlers mentioned above don't show anything. The only way to see the messages would be to proxy the WebSocket object as early as possible:

page.onInitialized = function(){
    page.evaluate(function(){
        (function(w){
            var oldWS = w.WebSocket;
            w.WebSocket = function(uri){
                this.ws = new oldWS(uri);
                ...
            };
            w.WebSocket.prototype.send = function(msg){
                w.callPhantom({type: "ws", sent: "msg"});
                this.ws.send(msg);
            };
            ...
        })(window);
    });
};
page.onCallback = function(data){
    console.log(JSON.stringify(data, undefined, 4));
};

1 我的测试实际上表明 websocket 回显页面 有效支持 v1.9.6 及更高版本,但不支持 v1.9.0.

1 My tests actually show that the websocket echo page works with v1.9.6 and up, but not v1.9.0.

这篇关于如何在 Phantom.js 中监控 WebSocket 通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆