Creating a web extension that streams the currently rendered HTML and CSS of a page to a Node.js server via WebSockets is an interesting project. Below is a complete guide to help you build this system, including:
- Creating the browser extension that captures the HTML and CSS, sends them over WebSockets, and updates on any user interaction.
- Setting up the Node.js server that receives the data, serves the rendered pages on specific routes, and lists all active clients.
Let's dive into each part step-by-step.
Part 1: Creating the Browser Extension
1.1. Set Up the Extension Structure
Create a new directory for your extension. Inside this directory, you'll need the following files:
manifest.json
content.js
background.js (optional, for background tasks)
- Any resources like icons (optional)
1.2. Create the manifest.json File
The manifest.json file tells the browser about your extension, what permissions it needs, and which files to load.
{
"manifest_version": 3,
"name": "HTML Streamer",
"version": "1.0",
"description": "Streams the current page's HTML and CSS to a Node.js server.",
"permissions": [
"scripting",
"activeTab",
"webNavigation"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_idle"
}
],
"host_permissions": ["<all_urls>"]
}
1.3. Implement the Content Script (content.js)
The content script runs in the context of web pages and can access the DOM.
// content.js
(function() {
// Replace with your Node.js server address and port
const SERVER_URL = 'ws://localhost:8080';
// Establish WebSocket connection
const socket = new WebSocket(SERVER_URL);
// Function to send HTML and CSS
const sendPageContent = () => {
const html = document.documentElement.outerHTML;
const styles = Array.from(document.styleSheets)
.map(sheet => {
try {
return Array.from(sheet.cssRules)
.map(rule => rule.cssText)
.join('');
} catch (e) {
// Handle CORS restrictions
return '';
}
})
.join('');
const data = {
type: 'pageContent',
html: html,
css: styles,
url: window.location.href
};
socket.send(JSON.stringify(data));
};
// Send content when socket opens
socket.addEventListener('open', () => {
sendPageContent();
});
// Listen for DOM changes (e.g., click events)
const observer = new MutationObserver(() => {
sendPageContent();
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
characterData: true
});
// Clean up when the socket closes
window.addEventListener('beforeunload', () => {
socket.close();
});
})();
Notes:
- The script captures the current HTML and attempts to retrieve the CSS from stylesheets.
- It sets up a WebSocket connection to the server.
- It uses a
MutationObserver to watch for changes in the DOM and sends updates accordingly.
- Due to cross-origin restrictions, accessing CSS rules from external stylesheets may fail. The script handles exceptions silently.
1.4. (Optional) Handle User Interactions
If you want to send specific user interactions (like clicks):
// Inside your IIFE in content.js
// Send click events
document.addEventListener('click', (event) => {
const data = {
type: 'userInteraction',
interaction: 'click',
target: event.target.outerHTML,
timestamp: Date.now()
};
socket.send(JSON.stringify(data));
});
Part 2: Setting Up the Node.js Server
2.1. Initialize Your Node.js Project
Create a new directory for your server and run:
npm init -y
2.2. Install Necessary Packages
npm install express ws
express for handling HTTP routes.
ws is a WebSocket implementation for Node.js.
2.3. Implement the Server (server.js)
// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const app = express();
const port = 3000;
// Serve static files (if any)
app.use(express.static('public'));
// Data structures to store client data
const clients = {};
// HTTP server
const server = http.createServer(app);
// WebSocket server
const wss = new WebSocket.Server({ server });
// Handle new WebSocket connections
wss.on('connection', (ws) => {
const clientId = generateId();
clients[clientId] = {
ws: ws,
html: '',
css: '',
url: ''
};
console.log(`Client ${clientId} connected`);
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
if (data.type === 'pageContent') {
clients[clientId].html = data.html;
clients[clientId].css = data.css;
clients[clientId].url = data.url;
} else if (data.type === 'userInteraction') {
// Handle user interactions if needed
console.log(`Interaction from ${clientId}:`, data);
}
} catch (e) {
console.error('Error parsing message:', e);
}
});
ws.on('close', () => {
console.log(`Client ${clientId} disconnected`);
delete clients[clientId];
});
});
// Generate a unique client ID
function generateId() {
return Math.random().toString(36).substr(2, 9);
}
// Route to list all active clients
app.get('/clients', (req, res) => {
res.json(Object.keys(clients));
});
// Route to render the client's page
app.get('/client/:id', (req, res) => {
const client = clients[req.params.id];
if (client) {
res.send(client.html);
} else {
res.status(404).send('Client not found');
}
});
// Start the server
server.listen(port, () => {
console.log(`Server is listening on http://localhost:${port}`);
});
Notes:
- The server keeps track of clients using an object, where each key is a unique
clientId.
- When a client sends
pageContent, it updates their stored HTML and CSS.
- There's an endpoint
/clients that returns a list of active client IDs.
- There's a dynamic route
/client/:id to view the stored HTML of a specific client.
2.4. Serve the CSS Properly (Optional)
If you want to serve the CSS along with the HTML, you'll need to adjust the way you're saving and sending the data.
Modify the /client/:id route:
app.get('/client/:id', (req, res) => {
const client = clients[req.params.id];
if (client) {
let htmlContent = client.html;
// Inject the CSS into a style tag in the head
const cssTag = `<style>${client.css}</style>`;
htmlContent = htmlContent.replace('</head>', `${cssTag}</head>`);
res.send(htmlContent);
} else {
res.status(404).send('Client not found');
}
});
Now, the CSS will be injected directly into the <head> section of the HTML when it's served.
2.5. Run the Server
Start your server:
node server.js
Part 3: Testing the System
3.1. Load the Extension in Your Browser
- Open your browser's extensions page (e.g.,
chrome://extensions/ in Chrome).
- Enable "Developer mode".
- Click "Load unpacked" and select your extension's directory.
3.2. Visit Any Web Page
Navigate to any web page. The extension should automatically:
- Connect to your Node.js server via WebSocket.
- Send the current page's HTML and CSS.
- Monitor for any DOM changes and send updates.
3.3. View the Rendered Pages on the Server
- Visit
http://localhost:3000/clients to see a list of active client IDs.
- Visit
http://localhost:3000/client/CLIENT_ID (replace CLIENT_ID with an actual ID from the list) to view the rendered page as captured by the extension.
3.4. Interact with the Page
As you interact with the page (click, type, etc.), the extension should detect DOM changes and send updated HTML to the server. Refresh the /client/CLIENT_ID page to see the updates.
Additional Enhancements
-
Handle CSS from External Stylesheets: Due to cross-origin policies, accessing CSS rules from external stylesheets can cause errors. To capture styles more reliably, consider using the getComputedStyle method on elements, although this can be more complex and resource-intensive.
-
Secure WebSocket Connection: If deploying over HTTPS, you'll need to use wss:// for secure WebSocket connections and handle certificates accordingly.
-
Authentication and Security: Implement authentication mechanisms to ensure only authorized extensions can connect and send data to your server.
-
Optimizing Updates: Instead of sending the entire HTML on every change, consider implementing a diff algorithm to send only the changes, reducing bandwidth usage.
-
Error Handling: Add robust error handling and logging on both the client and server sides.
Conclusion
You've now built a complete system where a browser extension streams the current page's HTML and CSS to a Node.js server via WebSockets. The server can display the rendered pages and provides a route to list all active clients.
This setup can be the foundation for more advanced applications like remote monitoring, collaborative browsing, or real-time content sharing.
Disclaimer: Always ensure you have permission to capture and transmit web page content, especially when dealing with sensitive information or restricted pages.