在 chrome 扩展中实现 websocket



我正在Chrome扩展中实现WebSocket。

我在后台编写了代码.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 
======"); };
}

当我打开弹出屏幕(index.html)时,将调用方法createWebSocketConnection(),这将创建一个WebSocket连接。

但是,一旦弹出窗口关闭,服务器控制台上就会打印一条消息,指出">Web 套接字已关闭

我有以下问题-

  1. 我应该在内容中建立 WebSocket 连接吗.js?
  2. 打开的每个网页是否具有不同的 WebSocket?
  3. 有什么方法可以在后台保存 WebSocket 对象.js?
  4. 在 chrome 扩展程序中实现 Web 套接字的最佳实践是什么?

提前感谢!

万岁!

我通过修改manifest.json解决了这个问题

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

我在background.js中实现了websockets。

以下是代码:

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

这取决于您希望实现目标的内容和方式。

如果每个扩展有一个持久WebSocket是你的目标(这是最有可能的情况),请在后台脚本中创建它。然后,您可以使用消息传递将消息中继到弹出窗口/内容。

如果您需要从内容/弹出页面直接与服务器对话,请在那里创建它。当内容页面或弹出窗口关闭时,您的WebSocket也将关闭。

Web 套接字将被关闭,因为弹出窗口有自己的上下文,每次打开弹出窗口时,它都会创建新对象,并且在关闭弹出窗口时,状态将被擦除,您需要在后台脚本中执行此逻辑! 正如上述开发人员提供的一些片段!

最新更新