Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ module("crx-extensions", "./tutorials/crx-extensions")
// Automation with MCP
module("mcp-devtools", "./tutorials/ai/mcp-devtools")
module("mcp-extension", "./tutorials/ai/mcp-extension")
module("intercepting-web-sockets", "./tutorials/intercepting-web-sockets")
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* Copyright 2026, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import com.teamdev.jxbrowser.browser.callback.InjectJsCallback;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.engine.RenderingMode;
import com.teamdev.jxbrowser.frame.Frame;
import com.teamdev.jxbrowser.js.JsFunctionCallback;
import com.teamdev.jxbrowser.js.JsObject;
import com.teamdev.jxbrowser.view.swing.BrowserView;
import java.awt.BorderLayout;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class WebSocketInterceptor {

public static void main(String[] args) {
var engine = Engine.newInstance(RenderingMode.HARDWARE_ACCELERATED);
var browser = engine.newBrowser();

// Inject JavaScript and register bridge functions.
browser.set(InjectJsCallback.class, params -> {
var frame = params.frame();
injectInterceptor(frame);
registerBridgeFunctions(frame);
return InjectJsCallback.Response.proceed();
});

SwingUtilities.invokeLater(() -> {
var view = BrowserView.newInstance(browser);

var frame = new JFrame("WebSocket Interceptor");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setVisible(true);
});

// Load the demo HTML page.
var html = loadResource("websocket-demo.html");
browser.navigation().loadHtml(html);
}

private static void injectInterceptor(Frame frame) {
var script = loadResource("websocket-interceptor.js");
frame.executeJavaScript(script);
}

private static void registerBridgeFunctions(Frame frame) {
JsObject window = frame.executeJavaScript("window");

window.putProperty("onWebSocketReceived", (JsFunctionCallback) args -> {
var data = (byte[]) args[0];
System.out.println("[RECEIVED] " + data);
return null;
});

window.putProperty("onWebSocketSent", (JsFunctionCallback) args -> {
var data = args[0].toString();
System.out.println("[SENT] " + data);
return null;
});
}

private static String loadResource(String resourceName) {
try (var stream = WebSocketInterceptor.class.getResourceAsStream(
"/" + resourceName)) {
if (stream == null) {
throw new RuntimeException(
"Resource not found: " + resourceName);
}
return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(
"Failed to load resource: " + resourceName, e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Interception Demo</title>
</head>
<body>
<h1>WebSocket Interception Demo</h1>
<button id="connect">Connect</button>
<button id="send" disabled>Send Message</button>
<button id="disconnect" disabled>Disconnect</button>
<div id="status">Not connected</div>

<script>
let socket = null;

document.getElementById('connect').addEventListener('click', () => {
socket = new WebSocket('wss://echo.websocket.org/');

socket.addEventListener('open', () => {
document.getElementById('status').textContent = 'Connected';
document.getElementById('connect').disabled = true;
document.getElementById('send').disabled = false;
document.getElementById('disconnect').disabled = false;
});

socket.addEventListener('close', () => {
document.getElementById('status').textContent = 'Disconnected';
document.getElementById('connect').disabled = false;
document.getElementById('send').disabled = true;
document.getElementById('disconnect').disabled = true;
});
});

document.getElementById('send').addEventListener('click', () => {
socket.send('Hello from browser at ' + new Date().toISOString());
});

document.getElementById('disconnect').addEventListener('click', () => {
socket.close();
});
</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Save reference to the native WebSocket.
const NativeWebSocket = window.WebSocket;

// Override the global WebSocket constructor.
window.WebSocket = function(url, protocols) {
const socket = new NativeWebSocket(url, protocols);

// Intercept incoming messages.
socket.addEventListener('message', (event) => {
if (window.onWebSocketReceived) {
window.onWebSocketReceived(event.data);
}
});

// Intercept outgoing messages.
const originalSend = socket.send;
socket.send = function(data) {
if (window.onWebSocketSent) {
window.onWebSocketSent(data);
}
originalSend.call(socket, data);
};

return socket;
};

// Preserve the prototype chain.
window.WebSocket.prototype = NativeWebSocket.prototype;