Skip to content

Instantly share code, notes, and snippets.

@vasilvestre
Last active June 1, 2021 20:22
Show Gist options
  • Save vasilvestre/ef5466a6b1d5a4e344ad6f1ef8c87199 to your computer and use it in GitHub Desktop.
Save vasilvestre/ef5466a6b1d5a4e344ad6f1ef8c87199 to your computer and use it in GitHub Desktop.
Chrome extension ws connect + read current tab + node js ws server

npm install ws

var ws = new WebSocket('ws://localhost:8088/post');
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete") {
ws.send(tab.url);
}
});
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["tabs","activeTab"]
}
const WebSocket = require('ws');
const url = require('url');
const wss = new WebSocket.Server({ port: 8088 });
wss.on('connection', function connection(ws, request) {
const pathname = url.parse(request.url).pathname;
var msg = '';
if (pathname === '/post') {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
msg = message;
});
}
if (pathname === '/get') {
ws.on('message', function incoming(message) {
console.log('sending : %s', message);
ws.send(msg);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment