I am developing one simple extension in which I want to show RealTime
data which is sending from my server through web socket connection.
I am using chrome's manifest v3 for that. I try to connect my extension with web socket through background.js
which is run on background of chrome as a service worker.
we can't access window
object in service worker JS(background.js) and even can't add more script in background JS. I was reading about it from last one week and still not find any solution.
does anyone know , how to connect web socket in service worker jS(background.js) so that, server can send data to the extension.
Any small help would be great helpful for me. please help me.
I'm still looking for a solution for the WebSockets myself as well.
However, you also mentioned that you couldn't add more scripts to the service worker background.js. There is a solution for that; service workers have a importScripts()
function (by the way, its not available in document/window). Here's a few examples:
//// Single Script
let scriptURL = '/js/otherScript.js';
try {
importScripts(scriptURL);
} catch (e) {
console.error('Error Loading Script', scriptURL);
console.error(e);
}
//// Multiple Scripts, Easy Way; Limited error detail
let scripts = [ '/js/script1.js', '/js/script2.js', '/js/script3.js' ];
try {
importScripts(scripts);
} catch (e) {
console.error(e);
}
//// Multiple Scripts, Manual foreach; More error detail
let scripts = [ '/js/script1.js', '/js/script2.js', '/js/script3.js' ];
let continueImport = true;
scripts.forEach(function(scriptURL) {
if (continueImport) {
try {
importScripts(scriptURL);
} catch (e) {
console.error('Error Loading Script', scriptURL);
console.error(e);
continueImport = false;
}
}
});
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