Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement websocket in chrome extension

I am implementing WebSocket in chrome extension.

I wrote the code in background.js

var websocket;
function createWebSocketConnection() {

    if('WebSocket' in window){
        websocket = new WebSocket(host);
        console.log("======== websocket ===========", websocket);

        websocket.onopen = function() {
            websocket.send("Hello");
        };

        websocket.onmessage = function (event) {
            var received_msg = JSON.parse(event.data);
            var notificationOptions = {
                type: "basic",
                title: received_msg.title,
                message: received_msg.message,
                iconUrl: "extension-icon.png"
            }
            chrome.notifications.create("", notificationOptions);
        };

        websocket.onclose = function() { alert("==== web socket closed 
======"); };
}

When I open the popup screen (index.html), the method createWebSocketConnection() is invoked, which will create a WebSocket connection.

But as soon as the popup is closed, a message is print on the Server console that "Web socket is closed.

I have following questions-

  1. Should I make WebSocket connection in content.js?
  2. Do each web page opened will have different WebSocket?
  3. Is there any way I can save the WebSocket object in the background.js?
  4. What is the best practice of implementing web socket in chrome extensions?

Thanks in advance!

like image 965
Pallavi Goyal Avatar asked Feb 12 '18 12:02

Pallavi Goyal


2 Answers

Hurray!

I solved this problem by modifying manifest.json

{
...
  "background": {
    ...
    "persistent": true
  },
...
}
like image 76
Николай Лубышев Avatar answered Sep 20 '22 20:09

Николай Лубышев


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;
    }
}
like image 36
Pallavi Goyal Avatar answered Sep 19 '22 20:09

Pallavi Goyal