Implement websocket in chrome extension

It depends on what and how you want to achieve your goal.

If one persistent WebSocket per extension is your aim, which is the most likely scenario, then create it in the background script. Then, you can relay the messages to popup/content using messaging.

If you need to talk from the content/popup page(s) directly to the server, then create it there. When content page or popup is closed, your WebSocket will be closed as well.


I implemented the websockets in the background.js.

Following is the code:

function createWebSocketConnection() {
    if('WebSocket' in window){
        chrome.storage.local.get("instance", function(data) {
            connect('wss://' + data.instance + '/ws/demoPushNotifications');
        });
    }
}

//Make a websocket connection with the server.
function connect(host) {
    if (websocket === undefined) {
        websocket = new WebSocket(host);
    }

    websocket.onopen = function() {
        chrome.storage.local.get(["username"], function(data) {
            websocket.send(JSON.stringify({userLoginId: data.username}));
        });
    };

    websocket.onmessage = function (event) {
        var received_msg = JSON.parse(event.data);
        var demoNotificationOptions = {
            type: "basic",
            title: received_msg.subject,
            message: received_msg.message,
            iconUrl: "images/demo-icon.png"
        }
        chrome.notifications.create("", demoNotificationOptions);
        updateToolbarBadge();
    };

    //If the websocket is closed but the session is still active, create new connection again
    websocket.onclose = function() {
        websocket = undefined;
        chrome.storage.local.get(['demo_session'], function(data) {
            if (data.demo_session) {
                createWebSocketConnection();
            }
        });
    };
}

//Close the websocket connection
function closeWebSocketConnection(username) {
    if (websocket != null || websocket != undefined) {
        websocket.close();
        websocket = undefined;
    }
}

Hurray!

I solved this problem by modifying manifest.json

{
...
  "background": {
    ...
    "persistent": true
  },
...
}