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-
Thanks in advance!
Hurray!
I solved this problem by modifying manifest.json
{
...
"background": {
...
"persistent": true
},
...
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With