Pallavi Goyal
Pallavi Goyal

Reputation: 566

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!

Upvotes: 22

Views: 24040

Answers (4)

varaprasadh
varaprasadh

Reputation: 505

web socket will be closed because popup has its own context, each time you open popup its creates new object and on closing of popup, the state will be erased, you need to do this logic at background scripts! as the above developers provided some snippets!

Upvotes: 1

Pallavi Goyal
Pallavi Goyal

Reputation: 566

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;
    }
}

Upvotes: 12

Hurray!

I solved this problem by modifying manifest.json

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

Upvotes: 14

Granga
Granga

Reputation: 1662

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.

Upvotes: 8

Related Questions