Is there some way to reconnect to Pusher if any error or non-connected state is found?
Here's our connection code:
var pusher = new Pusher('<apikey>', {encrypted: true});
var state = pusher.connection.state;
pusher.connection.bind( 'error', function( err ) {
console.log(err);
});
pusher.connection.bind('state_change', function(states) {
// states = {previous: 'oldState', current: 'newState'}
console.log(states);
});
The Pusher JavaScript library automatically attempts reconnection. You don't need to add any code to support this.
I can't find this anywhere in the Pusher docs, but I know this for a fact as I worked for Pusher for 2 years.
You can test by going to http://test.pusher.com/ and disconnecting from the Internet and then reconnecting again. The logging will show it is auto-reconnecting.
Related
I'm trying to ensure single worker session/window at a time.
In order to achieve this I have added a parameter closeExistingSessions to the createWorker and it's disconnecting (websocket) the other workerClient as expected.
Just wondering if there is a way to know the disconnect reason using this disconnected event listener so that I can show a relevant message to the end user.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(<ANY_ERROR_CODE_OR_SOMETHING_HERE?!>) {
console.log("Websocket has disconnected");
});
We are getting the reason (The reason the Worker websocket disconnected) as parameter to the disconnected callback.
const worker = new Twilio.TaskRouter.Worker(WORKER_TOKEN);
worker.on("disconnected", function(reason) {
console.log(reason.message);
});
And the reason for disconnecting due to existing sessions is 'Websocket disconnected due to new connection being registered'
Hope Twilio will keep their docs up to date
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 am developing a PWA that requires Push-Notifications. Sadly IOS/Safari does not support https://w3c.github.io/push-api/#pushmanager-interface for now, so I think i might have to wrap a native APP around in some way.
In Android (before their "Trusted Web Activities" was a thing) you could use a WebView to basically display a headless Chrome-View in your App. Whats the equivalent in IOS and how does the interaction between push-notifications and the Webapp (the browser need to jump to a specific page) work?
One more thing I need is integration with our companys Mobile Device Management, which is Microsoft Intune. Having integrated MDMs in Android in the past i Know that this might be a major pain in the a**, so i'm considering to build the wrapper myself, for maximum flexibility. Another option would be something like Ionic, not sure now.
This may not necessarily work in your situation, but I had the exact same issue with a PWA for Safari and I solved it by just using long polling. It will allow you to get around all of the limitations with Safari and I was able to redirect and load sections within our SPA.
async function subscribe() {
let response = await fetch("/subscribe");
if (response.status == 502) {
// Status 502 is a connection timeout error,
// may happen when the connection was pending for too long,
// and the remote server or a proxy closed it
// let's reconnect
await subscribe();
} else if (response.status != 200) {
// An error - let's show it
showMessage(response.statusText);
// Reconnect in one second
await new Promise(resolve => setTimeout(resolve, 1000));
await subscribe();
} else {
// Get and show the message
let message = await response.text();
showMessage(message);
// Call subscribe() again to get the next message
await subscribe();
}
}
subscribe();
https://javascript.info/long-polling
In my angular6 website with ASP.NET server application ,
I want the singnalR client should always stay connected with Hub(Server). For that purpose started the connection on disconnected event with below code snap.
this.connection.start().done((data: any) => {
console.log('Now connected');
this.connectionId = this.connection.id;
this.connectionEstablished.emit(true);
this.connectionExists = true;
}).fail((error: any) => {
this.connectionEstablished.emit(false);
});
this.connection.reconnecting(() => {
this.tryingToReconnect = true;
});
this.connection.reconnected(() => {
this.tryingToReconnect = false;
});
this.connection.error((error: any) => {
this.initialize();
});
this.connection.disconnected(() => {
if (this.tryingToReconnect) {
setTimeout(() => {
this.initialize();
}, 5000);
}
});;
Because of that above code, signalr creates the problem such as
crashes the client browser and memory leaks in below cases such as,
If there is problem in client internet connection for some hours , that time singalr continuously tries to create the connection with hub. Because of internet problem , logging the connection error in browser console infinitely until the successful connection with hub
If i close the server, that time also singalR logging the connection error in browser console infinitely until the successful connection with hub
How to rectify the problems for signalr always stay connected with Hub?
I would create an incremental value and each reconnect time out would be increased and showing a retry now option, same way Gmail does, is a good practice and would solve both problems.
I'm trying to establish a communication channel between an installing service worker and an activated service worker.
I've tried to do the following:
on the installing service worker:
if ((self.registration.active == null) ||
(self.registration.active.state != "activated")) {
return;
}
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event){
if (event.data.error) {
console.log("got error from active");
}
else {
console.log("got answer from active");
}
};
self.registration.active.postMessage({message: 'hey', port: messageChannel.port2}, [messageChannel.port2]);
on the active service worker:
self.addEventListener('message', function(event) {
console.log('received message');
});
This isn't working, I'm getting nothing...
Ideas?
Here's how I ended up implementing this.
Each serviceWorker at startup (code at the worker's global scope) connects to a broadcast channel like so:
var comChannel = new BroadcastChannel('SWCom');
comChannel.addEventListener('message', event => {
handleMessageEvent(event);
});
This channel is shared only between service workers.
To post a message to other SW, a SW can just broadcast on the channel comChannel.postMessage('hey there'); and any registered listener will be invoked.
One complication I had, not really related to the channel, is that I had a hard time identifying each SW life cycle state. If I want to communicate between SW it can't really serve any purpose if I don't know who's whom within each one of them. A SW cannot currently get a ref to its own ServiveWorker object, there's an open issue about it in the standard - https://github.com/w3c/ServiceWorker/issues/1077
In my usecase, I bypassed this limitation by performing the communication upon install (fits my needs...), like so:
self.addEventListener('install', function(event) {
if (self.registration.active != null) {
// if we got here it means this is a new SW that's
// starting install and there's an active one running.
// So we can send a message on the broadcast channel,
// whomever answers should be the active SW.
}
// ..
// installation code
// ..
}
One thing to note - I'm not sure this is well implemented.
I believe there are other states a SW can be at (redundant, deleted?, others?), so maybe there can be more then two ServiceWorkers alive, and then the assumption on the identity of the answering side on the channel might be wrong...
Jake provides some excellent examples of messaging that you may be able to derive a solution from. https://gist.github.com/jakearchibald/a1ca502713f41dfb77172be4523a9a4c
You may need to use the page itself as a proxy for sending/receiving messages between Service workers:
[SW1] <== message ==> [Page JS] <== message ==> [SW2]