扩展如何监听 WebSocket? (如果 WebSocket 在 iframe 中怎么办?)

How can an extension listen to a WebSocket? (and what if the WebSocket is within an iframe?)

我正在编写一个需要监听浏览器和服务器之间通信的 Firefox 扩展。对于 HTTP 通信,我在后台脚本中使用 webRequest 库。但是根据this Mozilla bug report,我不能使用webRequest来拦截WebSocket消息。我的扩展如何监听 WebSocket 通信?

更新:

我已经injected my ,但从未调用过!我正在尝试收听的 WebSocket 位于 iframe 内。这重要吗?

收听 WebSocket 通信的唯一方法是 inject a 进入站点代码并让它向您中继消息。您的代码应如下所示:

manifest.json

{
  ...
  "content_scripts": [
    {
      "matches": [
        "<website-url>",    
      ],
      "js": ["content/syringe.js"]
    }
  ],
  "web_accessible_resources": ["lib/socket-sniffer.js"]
}

content/syringe.js

var s = document.createElement('script');
s.src = browser.runtime.getURL('lib/socket-sniffer.js');
s.onload = function() {
    this.remove();
};

lib/socket-sniffer.js

(function() {
  var OrigWebSocket = window.WebSocket;
  var callWebSocket = OrigWebSocket.apply.bind(OrigWebSocket);
  var wsAddListener = OrigWebSocket.prototype.addEventListener;
  wsAddListener = wsAddListener.call.bind(wsAddListener);
  window.WebSocket = function WebSocket(url, protocols) {
    var ws;
    if (!(this instanceof WebSocket)) {
      // Called without 'new' (browsers will throw an error).
      ws = callWebSocket(this, arguments);
    } else if (arguments.length === 1) {
      ws = new OrigWebSocket(url);
    } else if (arguments.length >= 2) {
      ws = new OrigWebSocket(url, protocols);
    } else { // No arguments (browsers will throw an error)
      ws = new OrigWebSocket();
    }

    wsAddListener(ws, 'message', function(event) {
      console.log("Received:", event);
    });
    return ws;
  }.bind();
  window.WebSocket.prototype = OrigWebSocket.prototype;
  window.WebSocket.prototype.constructor = window.WebSocket;

  var wsSend = OrigWebSocket.prototype.send;
  wsSend = wsSend.apply.bind(wsSend);
  OrigWebSocket.prototype.send = function(data) {
    console.log("Sent:", data);
    return wsSend(this, arguments);
  };
})();

(document.head || document.documentElement).appendChild(s);

以上代码的所有功劳显然归功于上面链接的海报。为了方便起见,我把tt复制在这里。

更新:

是的,WebSocket 在 iframe 中确实很重要!默认情况下,扩展仅加载在最顶层的框架中。要将其加载到 iframe 中,您必须将 "all_frames": true 添加到 manifest.json:

manifest.json

{
  ...
  "content_scripts": [
    {
      "matches": [
        "<website-url>",    
      ],
      "all_frames": true,      
      "js": ["content/syringe.js"]
    }
  ],
  "web_accessible_resources": ["lib/socket-sniffer.js"]
}

如果您想阅读更多内容,请阅读 all_framesthe documentation