How to Intercept Sockets Using Playwright

April 28, 2025 note-to-self python automation

Intercept sockets using playwright with dev console trick.


from playwright.sync_api import sync_playwright import time import re import sys import argparse from PIL import Image import os import PIL import glob from urllib.parse import urlparse parser = argparse.ArgumentParser() goHeadless = False with sync_playwright() as p: browser_types = { "chrome": p.chromium, } emulations = { '3-laptop': '1280x1024', } for browser_type in browser_types: for emulation in emulations: browser = browser_types[browser_type].launch(headless=goHeadless) try: if isinstance(emulations[emulation], str): splittedEmulation = emulations[emulation].split('x') context = browser.new_context(viewport={'width': int(splittedEmulation[0]), 'height': int(splittedEmulation[1])}) else: context = browser.new_context(**emulations[emulation]) except Exception as e: print(e) continue page = context.new_page() for url in sys.argv: if (url == sys.argv[0]): continue; print(url) page.goto(url) players = page.evaluate(""" () => { var players = [] let s = WebSocket.prototype.send; WebSocket.prototype.send = function(json) { if (!this._oh) { this._oh = 1; this.addEventListener('message', function(e) { if (b.msg == 'added') { players.push(e.data); } }); } return s.apply(this, arguments); }; return players; } """) print(players) browser.close()
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.