There is a page (game), which communicate via WebSocket to the server. I can see the data (frames) in the Chrome Developer Tool. Is it possible to access / modify this communica
Currently, the only way to access or modify Websocket traffic is to use a content script to inject a script that replaces the WebSocket
constructor with your own wrapper. This wrapper should behave like the original WebSocket implementation, but you can add more stuff, like logging the sent/received messages to your extension.
To prevent sites from breaking, you must make sure that your WebSocket
wrapper is fully standard-compliant. The interface that has to be implemented is documented at http://www.whatwg.org/specs/web-apps/current-work/multipage/network.html#the-websocket-interface.
For inspiration on how to wrap a DOM constructor, see e.g. my wrapper for Worker. You are free to re-use parts of the code (e.g. the implementation of the EventTarget
interface, which is also a requirement of the WebSocket
API).
More emphasis: Make sure that your implementation adheres to the interface of the standard WebSocket API, or you could break some sites!
There is a WebSocket-Wrapper, you can use it to access WebSocket traffic:
https://github.com/gorhill/chromium-websocket-wrapper/blob/master/chromium-websocket-wrapper.js
Seems like the bug is fixed and available. In the manifest.json you need to explicitly specify the permissions
{
...
"permissions": ["webRequest", "ws://*/*", "wss://*/*"]
...
}
and in the network filters it should be specified as a websocket request.
const networkFilters = {
urls: [
"wss://echo.websocket.org/*"
]
};
chrome.webRequest.onBeforeRequest.addListener((details) => {
const { tabId, requestId } = details;
// do stuff here
}, networkFilters);
Judging from discussion on this bug, there is currently no API to intercept WebSocket traffic, unlike normal requests with chrome.webRequest
. It's assigned but not completed yet.
Edit: recent (as of Nov 2016) activity on the bug suggests a patch in the works.
I came across this question and tried solutions above, unfortunately the scripts in my target site still found WebSocket has been tampered and broke, which is bad.
So I come up with my own solution:
var ws = window.WebSocket;
window.WebSocket = function(a,b){
var ret = new ws(a,b);
let handle = setInterval(function(){
if(ret.onmessage){
clearInterval(handle);
let o = ret.onmessage;
ret.onmessage = function(m){
//do what your want to m
o(m);
};
}
},50);
return ret;
}
If the site you want to inspect does use WebSocket, I will definitely assign to onmessage
sometime after creating WebSocket object, just check it periodically and reassign it with your own function.