I am developing a chat application using firebase with ionic 3. I have to change status to 'offline' when disconnected from the internet.
I have referred to the following sites:
1) https://firebase.google.com/docs/database/web/offline-capabilities
2) https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect
this.disconnectSubscription = this.network
.onDisconnect()
.subscribe(() => {
this.online = false;
var userLastOnlineRef = firebase.database().ref('/accounts/'this.loggedInUserId);
userLastOnlineRef.onDisconnect().set({status:offline});
});
When I turn off the internet connection the status of offline will not get changed.
You can listen for online and offline event like this
window.addEventListener("online", this.doSomethingWhenOnline);
window.addEventListener("offline", this.doSomethingWhenOffline);
doSomethingWhenOnline() {
}
doSomethingWhenOffline() {
}
Related
Web push works fine from iframe in local but when i uploaded to cloud server then it does not work in only chrome or chromium browser.
I have developed a webpush micro-service that serve from a Iframe. That works fine in local but when i uploaded to cloud server then it does not work in only chrome or chromium browser. You can check from https:alemran.me (click ^ icon from bot).
Web Worker:
self.addEventListener('push', function (event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
const sendNotification = (title, body ) => {
return self.registration.showNotification(title,
body
);
};
if (event.data) {
const message = JSON.parse(event.data.text());
event.waitUntil(sendNotification(message.title,message.message));
}
});
There is no error show in console
You can open a new window with a url and get permission from user....
Like :
let win = window.open("your url", "_blank");
let winInterval = window.setInterval(function() {
if (win.closed !== false) {
window.clearInterval(winInterval );
//check your api for user subscription status
}
}, 200);
I have deployed my javascript desktop notification code on the web server but it is not working. It's working on my localhost properly. Can somebody help me out?
JavaScript Snippet
function showNotifaication() {
if (!("Notification" in window)) {
alert("Desktop notifications is not supported by this browser. Try another.");
return;
} else if (Notification.permission === "granted") {
var myNotification = new Notification("Twitter", {
icon: "https://pbs.twimg.com/profile_images/875087697177567232/Qfy0kRIP_400x400.jpg",
body: "Follow me on Twitter."
});
myNotification.onclick = function () {
window.open("https://twitter.com/google");
};
} else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (userPermission) {
if (userPermission === "granted") {
var myNotification = new Notification("Google", {
icon: "https://pbs.twimg.com/profile_images/839721704163155970/LI_TRk1z_400x400.jpg",
body: "Search on the Web."
});
myNotification.onclick = function () {
window.open("http://www.google.com");
};
}
});
}
}
and the button code
<button onclick="showNotifaication();">Show Notification</button>
All the above code works fine for the local machine whenever I have deployed it on the Apache server it will not work. One thing that I have noticed that my browser has already blocked the Notification and it is disabled also. No option for enables it.
From MDN, it looks like starting from Chrome 62, notificatin API is available in secure contexts only, i.e. only through localhost or a website running on HTTPS.
JavaScript desktop notification only works with HTTPS connection.
I am trying to check if USB Debugging is turned on or off through NPM/Node. As soon as an android phone is connected to my system and USB Debugging is turned off, then i need to show a prompt to user to enable usb debugging on his phone.
According to my research, every device (Scanner/Phones/USB) connected to my system has a unique GUID which helps me to distinguish which device is connected. Further, i'm not able to fetch the usb debugging details.
Please help!
I want this property which is in this link
Code which i have written so far is on the basis of iSerialNumber but i want to distinguish it on the basis of BUS-TYPE GUID.
var usb = require('usb');
usb.on('attach', function(device)
{
var devices = usb.getDeviceList();
var check = devices[0].deviceDescriptor;
if(check.iSerialNumber == '3')
{
console.log("Please enable USB Debugging");
}
else
{
console.log("Connect an Android device");
}
});
Here is the latest code which i have tried, but it works only for Samsung devices:-
var usbDetect = require('usb-detection');
var Promise = require('bluebird');
var adb = require('adbkit');
var client = adb.createClient();
usbDetect.on('add', function(dev) {
setTimeout(checkAndyDevice, 1500);
});
var checkAndyDevice = function(){
client.listDevices()
.then(function(devices) {
return Promise.map(devices, function() {
return devices;
})
})
.then(function(id) {
if((JSON.stringify(id)) == '[]')
{
console.log("Please enable Usb Debugging option from your Android device");
}
})
.catch(function(err) {
console.error('Something went wrong:', err.stack)
});
};
I am connection through Vertx eventbus (SockJS to my Java based backend. Everything work fine, However, I cannot find a way to send an initial message.
Is there a way to send back data when SockJS bridge receives SOCKET_CREATED to the sockjs browser side?
Thank you.
Taken from their documentation:
if (event.type() == SOCKET_CREATED || event.type() == SOCKET_CLOSED)
{
//...
vertx.eventBus().publish("fromServer", jmsg.toJSONString());
}
Your event instantiation may be different, but that would be how you check for the specific event and run code after it has occurred
You can check this code , where I'm using EventBus.
Here is the Reference code
this.eventBus = new EventBus(this.URL);
this.eventBus.onopen = (e) => {
this._opened = true;
console.log("open connection");
this.callHandlers('open', e);
this.eventBus.publish("http://localhost:8082", "USER LOGIN INFO");
this.eventBus.registerHandler("http://localhost:8081/pushNotification", function (error, message) {
console.log(message.body);
//$("<div title='Basic dialog'>Test message</div>").dialog();
});
}
this.eventBus.onclose = (e) => {
this.callHandlers('close', e);
}
}
Looks like Service Worker runs in a worker context and has no access to the DOM. However, once Service Worker installed, I want my users to know that the app will now work offline. How can I do that?
When the Service Worker is in activated state, this is the perfect time to display the toast 'Content is cached for offline use'. Try something below code while registering your service worker.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
// updatefound is fired if service-worker.js changes.
reg.onupdatefound = function() {
var installingWorker = reg.installing;
installingWorker.onstatechange = function() {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// It's the perfect time to display a "New content is available; please refresh."
// message in the page's interface.
console.log('New or updated content is available.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
console.log('Content is now available offline!');
}
break;
case 'redundant':
console.error('The installing service worker became redundant.');
break;
}
};
};
}).catch(function(e) {
console.error('Error during service worker registration:', e);
});
}
After testing #Prototype Chain's answer above, I wanted to use named functions as opposed to nested anonymous functions as event handlers to make code more pleasant to look at for my taste, and hopefully easier to understand later/for others.
But only after spending some time sorting docs, I managed to listen correct events on correct objects. So sharing my working example here in hopes of saving someone else from tedious process.
// make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/sw.js')
.then(function (registration) {
console.log("ServiceWorker registered");
// updatefound event is fired if sw.js changed
registration.onupdatefound = swUpdated;
}).catch(function (e) {
console.log("Failed to register ServiceWorker", e);
})
}
function swUpdated(e) {
console.log('swUpdated');
// get the SW which being installed
var sw = e.target.installing;
// listen for installation stage changes
sw.onstatechange = swInstallationStateChanged;
}
function swInstallationStateChanged(e) {
// get the SW which being installed
var sw = e.target;
console.log('swInstallationStateChanged: ' + sw.state);
if (sw.state == 'installed') {
// is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
if (navigator.serviceWorker.controller) {
console.log('Content has updated!');
} else {
console.log('Content is now available offline!');
}
}
if (sw.state == 'activated') {
// new|updated SW is now activated.
console.log('SW is activated!');
}
}