Node JS + Socket.IO + Chrome Extension Integration

Written by hackernoon-archives | Published 2017/07/05
Tech Story Tags: nodejs | chrome | chrome-extension | javascript | socketio

TLDRvia the TL;DR App

The followings are the steps to integrate Socket.io in Chrome extension. We wanted to allow message passing in our Chrome application, and socket.io is the best option to do so. Chrome extension doesn’t allow its native socket connection due to security issues. But we can achieve this via JavaScript socket connection. On the server side, we have used Node JS. The following is the architecture of Node JS, Chrome extension, and Socket.io integration.

SERVER SIDE CODE (NODE JS)

Step 1:

In your express application, add socket.io via installing socket.io

npm install socket.io

Step 2:

Now add this dependency in your app. js file.

var express = require('express');
var app = express();

// Socket connection

/* Creates new HTTP server for socket */
var socketServer = require('http').createServer(app);
var io = require('socket.io')(socketServer);

/* Listen for socket connection on port 3002 */
socketServer.listen(3002, function(){
  console.log('Socket server listening on : 3002');
});

/* This event will emit when client connects to the socket server */
io.on('connection', function(socket){
  console.log('Socket connection established');
});

/* Create HTTP server for node application */
var server = http.createServer(app);

/* Node application will be running on 3000 port */
server.listen(3000);

CLIENT SIDE CODE

Step 1:

In your chrome extension add socket.io.js in your index.html you can find it on:

https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js

Step 2:

Now add the following script in your js file where you want to establish your connection.

/* Connects to the socket server */
var socket = io.connect('http://localhost:3002');
socket.on('connect', function() {
  console.log('Client connected');
});

Hope Shared code would be helpful. For Facebook, Google and Slack integration stay tune. We will be back soon.

Follow us on @thirdrocktechkno on twitter and fb.com/ThirdRockTechkno on Facebook.

Do share your feedback. :)


Published by HackerNoon on 2017/07/05