How can I console log the send/receive data of a websocket using Chrome Web Extension?

215 views Asked by At

So what I'm trying to do is, using a chrome web extension, attach to a websocket connection, instead of creating a new connection, and console log the data which is being sent and received. My issue is, I think I'm not being able to add the listener to the websocket.js from the site, because I can't get the console.log ("Matched..")

Here's my html/js/websocket codes:

Index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket Example</title>
  </head>
  <body>
    <div id="messages"></div>
    <script src="websocket.js"></script>
    <script src="main.js"></script>
  </body>
</html>

Here's main.js

function displayMessage(message) {
  const messagesDiv = document.getElementById("messages");
  messagesDiv.innerHTML += `<p>${message}</p>`;
}

function startSendingMessages() {
  setInterval(() => {
    sendMessage("Hello from WebSocket!");
  }, 5000);
}

document.addEventListener("DOMContentLoaded", () => {
  initWebSocket();
  startSendingMessages();
});

And here is websocket.js

let socket = null;

function initWebSocket() {
  socket = new WebSocket("wss://socketsbay.com/wss/v2/1/demo/");

  socket.addEventListener("open", (event) => {
    console.log("WebSocket is open");
  });

  socket.addEventListener("close", (event) => {
    console.log("WebSocket is closed");
  });

  socket.addEventListener("error", (event) => {
    console.error("WebSocket error:", event);
  });
}

function sendMessage(message) {
  if (socket.readyState === WebSocket.OPEN) {
    socket.send(message);
  } else {
    console.error("WebSocket not open. Message not sent.");
  }
}

And here's the web browser extension codes: manifest.json:

{
  "manifest_version": 3,
  "name": "Socket Logger Extension",
  "version": "1.0",
  "description": "Logs socket messages in all frames",
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules_1.json"
      }
    ]
  },
  "permissions": ["declarativeNetRequest", "declarativeNetRequestFeedback"],
  "host_permissions": ["http://*/*", "https://*/*"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["http://127.0.0.1:5500/*"],
      "js": ["content_script.js"],
      "all_frames": true
    }
  ]
}

rules_1.json:

[
  {
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "||127.0.0.1:5500/websocket.js",
      "resourceTypes": ["main_frame"]
    }
  }
]

background.js:

chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((e) => {
  console.log("Matched..");
  chrome.scripting.executeScript({
    target: { tabId: details.tabId },
    files: ["content_script.js"],
  });
});

and content_script.js:

function interceptWebSocket() {
  const originalWebSocket = window.WebSocket;
  window.WebSocket = function (url, ...args) {
    const socket = new originalWebSocket(url, ...args);

    socket.addEventListener("message", (event) => {
      console.log("Received:", event.data);
    });

    socket.addEventListener("send", (event) => {
      console.log("Sent:", event.data);
    });

    socket.addEventListener("open", (event) => {
      console.log("WebSocket is open");
    });

    socket.addEventListener("close", (event) => {
      console.log("WebSocket is closed");
    });

    socket.addEventListener("error", (event) => {
      console.error("WebSocket error:", event);
    });

    return socket;
  };
}

interceptWebSocket();
1

There are 1 answers

1
Juan Marin On

Override the WebSocket send method to intercept the data being sent:

const originalSend = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
    console.log("Sent:", data);
    return originalSend.apply(this, arguments);
};