在Chrome扩展程序中实现WebSocket

Pal*_*yal 7 websocket google-chrome-extension

我正在Chrome扩展中实现WebSocket。

我在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 
======"); };
}
Run Code Online (Sandbox Code Playgroud)

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

但是,一旦关闭弹出窗口,就会在服务器控制台上显示一条消息,指出“ Web socket已关闭”

我有以下问题-

  1. 我应该在content.js中建立WebSocket连接吗?
  2. 打开的每个网页都会有不同的WebSocket吗?
  3. 有什么办法可以将WebSocket对象保存在background.js中?
  4. 在Chrome扩展程序中实现Web套接字的最佳做法是什么?

提前致谢!

Pal*_*yal 8

我在background.js.

以下是代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Gra*_*nga 7

这取决于您想要实现目标的方式和方式。

如果WebSocket您的目标是每个扩展一个持久化,这是最有可能的场景,然后在后台脚本中创建它。然后,您可以使用中继消息弹出/内容的消息

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


Ник*_*шев 6

欢呼!

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

{
...
  "background": {
    ...
    "persistent": true
  },
...
}
Run Code Online (Sandbox Code Playgroud)

  • @Notflip 保持后台脚本持续活动的唯一情况是扩展程序使用 chrome.webRequest API 来阻止或修改网络请求。webRequest API 与非持久后台页面不兼容。 (2认同)