Reputation: 414
I have an application which I want to connect with a Chrome Extension, but I always get the warning
socket.js:85 Event handler of 'beforeunload' event must be added on the initial evaluation of worker script.
I am using the Chrome Extension Boilerplate: https://github.com/lxieyang/chrome-extension-boilerplate-react If I import it into my popup.js everything works fine, but the problem is that the popup has to be open to run the code - so I decided to move it into the servicer_worker. Is there a workaround to run the sockets in the service_worker or whats the best way to keep the communication between a extension and a server with sockets?
I imported the socket.io-client into my service_worker index.js:
import io from 'socket.io-client';
const socket = io("http://localhost:3002");
socket.on("calibration", function (data) {
console.log("calibration", data);
});
manifest.json
{
"manifest_version": 3,
"name": "Chrome Extension with React & Webpack",
"description": "A chrome extension boilerplate built with React 17, Webpack 5, and Webpack Dev Server 4",
"options_page": "options.html",
"background": { "service_worker": "background.bundle.js" },
"action": {
"default_popup": "popup.html",
"default_icon": "icon-34.png"
},
"chrome_url_overrides": {
"newtab": "newtab.html"
},
"icons": {
"128": "icon-128.png"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*", "<all_urls>"],
"js": ["contentScript.bundle.js"],
"css": ["content.styles.css"]
}
],
"devtools_page": "devtools.html",
"web_accessible_resources": [
{
"resources": ["content.styles.css", "icon-128.png", "icon-34.png"],
"matches": []
}
]
}
Upvotes: 2
Views: 1628
Reputation: 73566
The warning means that socket.io is not compatible with service workers, so it may be impossible to make it work there without changing its source code, however if it works then the warning can be ignored, otherwise you'll need to find another library or write one yourself.
Another problem is that service worker's lifetime is limited to 30 seconds with no external connection or five minutes if there is one, so you'll have to keep it running artificially.
An alternative solution in case your extension is meant to be used only/mostly in devtools is to connect inside your devtools_page
script so it works as a replacement for the background script, more info.
In the future there may be a better solution: silent Push subscriptions.
Upvotes: 2