I am making an extension on the manifest version 3, and Service Worker is used there, how do I listen to events that the user is online or offline? Events like online or offline don't work in Service Worker. navigator.onLine works but I need events
Here's what I tried
self.addEventListener('online', function () {
console.log('online')
})
self.addEventListener('offline', function () {
console.log('offline')
})
Related
I'm trying to use background periodic sync for my website. I'm using localhost and registering the periodicsync event at 1*1000 ms, but that doesn't fire at all.
I had a look at this demo, but even if I install the website as an app, it won't fire at all.
Using chrome 87.0.4280.66.
It works however if I manually trigger the periodic sync event from Application developer window.
The periodicsync event will only register correctly when the app is installed as a PWA in a 'most' webkit based browsers only
https://developer.mozilla.org/en-US/docs/Web/API/Web_Periodic_Background_Synchronization_API
The conditions as to whe this will actually fire is unclear and is dependent on some wooly factors such as the users engagement with the website.
That is why the perameter that can be set when registering for the periodic sync is minInterval
This block will help you to register for it successfully, I am, unfortunatly unclear on what the 'real world' scenarios in which the peridic sync will fire:
const status = await navigator.permissions.query({
// #ts-ignore
name: 'periodic-background-sync',
});
if (status.state === 'granted') {
navigator.serviceWorker.ready.then(async (sw: any) => {
await sw.periodicSync.register('periodicsync', {
minInterval: 1000,
});
})
.catch(error => {
console.error('[BackgroundSync] Error: ' + JSON.stringify(error, null, 2));
});
}
else {
console.error('[BackgroundSync] Does not have permission');
}
}
I'm currently using the latest Workbox version 4.3.1 with workbox-window, I'm offering a page reload for users by listening to the waiting event, I'm using the code provided on the Advanced Recipes page of the Workbox documentation.
The code on the page:
if ('serviceWorker' in navigator) {
const wb = new Workbox('/sw.js');
// Add an event listener to detect when the registered
// service worker has installed but is waiting to activate.
wb.addEventListener('waiting', (event) => {
// `event.wasWaitingBeforeRegister` will be false if this is
// the first time the updated service worker is waiting.
// When `event.wasWaitingBeforeRegister` is true, a previously
// updated same service worker is still waiting.
// You may want to customize the UI prompt accordingly.
// Assumes your app has some sort of prompt UI element
// that a user can either accept or reject.
const prompt = createUIPrompt({
onAccept: async () => {
// Assuming the user accepted the update, set up a listener
// that will reload the page as soon as the previously waiting
// service worker has taken control.
wb.addEventListener('controlling', (event) => {
window.location.reload();
});
// Send a message telling the service worker to skip waiting.
// This will trigger the `controlling` event handler above.
// Note: for this to work, you have to add a message
// listener in your service worker. See below.
wb.messageSW({type: 'SKIP_WAITING'});
},
onReject: () => {
prompt.dismiss();
}
})
});
wb.register();
}
The code in the service worker file:
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
I have tested it and it's working just fine, I can show a snackbar to the user and let them know that there's an update and when they accept, a SKIP_WAITING message is sent to the service worker to call skipWaiting().
Let's assume that the user did not accept the reload prompt and refreshed the page or navigated to another page, the new service worker will be kept waiting and won't activate and that's the normal behavior, but my question is how can I show this reload prompt to the user if they refreshed or navigated to another page? It seems that the waiting event is only fired once.
Is it possible to make HTTP requests in background with service worker, when users are not visiting my webpage. I want to make periodic requests to my webpage (e.g. 3 seconds)?
There is a feature called periodicSync, but i didn't understand how to use it.
I've not tried implementing this but for me the clearest overview has been this explanation.
Making periodic requests involves first handling the Service Worker ready event, invoking the periodicSync.register() function with config options. The register() function returns a Promise that allows you to deal with success or rejection of the periodic sync registration.
registration.periodicSync.register()
Pass a 'config' object parameter with the following properties:
tag
minPeriod
powerState
networkState
You may then register listeners against the periodicSync event. E.g (slightly simplified example based on the explanation.
self.addEventListener('periodicsync', function(event) {
if (event.registration.tag == 'my-tag') {
event.waitUntil(doTheWork()); // "do the work" asynchronously via a Promise.
}
else {
// unknown sync, may be old, best to unregister
event.registration.unregister();
}
});
I have deployed my business network using node-red and local composer over fabric. I would like to listen to an event in node-red. I am able to submit the transaction successfully but not able to see the notification emitted by event in the same transaction on debug console in node-red.
composer nodes are latest and Composer is 0.16v. Event url port is 7053. I have attached two images below.
Transaction Submitted - shipmentreceived. When the transaction processor function is executed for this transaction, event is emitted as mentioned below:
var basicEvent=getFactory().newEvent('org.acme.shipping.perishable','ShipmentNotification');
basicEvent.shipmentStatus = shipment.status;
emit(basicEvent);
Model File:
event ShipmentNotification{
o String shipmentStatus
}
Node-red - Submitting and Listening event
This could be error
see https://medium.com/#CazChurchUk/integrate-your-blockchain-with-anything-using-hyperledger-composer-and-nodered-4226676f7e54
it needs to be updated to use 'business network cards' not 'profiles' in the NodeRed node widgets / flow, but the same principle applies where subscribing to events are concerned.
There are running examples of SignalR, but in those, i have seen that the process is started by the client i.e. every piece of code contains following similar lines
$.connection.hub.start().done(function () {
$('#mybutton').click(function () {
notifier.server.doLongOperation();
});
});
The process on server starts on $('#mybutton').click and then responds.
Is my understanding correct? If yes then is it possible to start the process by Server? I mean Server will push messages to all clients without any triggering from the client side.
This didn't work
var context = GlobalHost.ConnectionManager.GetHubContext<Broadcast>();
context.Clients.All.Send(message);
My bad, method name on client side was incorrect. Problem solved
Yes it is possible to send server initiated "messages" from the server to clients. Note that you have to call a method on the client. Note that it's a RPC/Remoting type of communication.
On the server you'd have a code like this:
Clients.All.Say("Hello World!");
where the client needs to define a function:
myHub.client.say = function (message) {
console.log(message);
});
see the SignalR documentation