Event when session restored after browser restart? - google-chrome-extension

Is there a way detect when browser (re)started and session restored?
I've tried
chrome.sessions.onChanged.addListener((...args) =>
{
console.log("chrome.sessions.onChanged fired", args);
});
but nothing logged.
I'm trying store some data for each tab and since tab.id and tab.windowId changes each time browser (re)started, I need to get notified when session is restored on startup, so I could update tabs database with new data.

Related

Firebase / Node.js, correct usage of on.Disconnect()

I have a node.js, the monitors a queue on Firebase, to send GCM Push notifications. Works fine.
It also updates an "online" status on firebase via .onDisconnect(), so one can easily see if the Node.js server is online and running.
Problem: after some time it will show "disconnected" even when the listener is still connected and running fine.
const NODESERVERONLINE="NodeSeverStatus";
var ref = new Firebase(FBURL+FBKEY_GCM_QUEUE);
ref.child("NODESERVERONLINE").set("Online");
ref.child("NODESERVERONLINE").onDisconnect().set("Offline!");
ref.on("child_added",function(snapshot, prevChild){
If (snapshot.key()!=NODESERVERONLINE) DO_GCM_PUSH(snapshot.val());
}, function(errorObject){
console.log("Error reading Firebase: " + errorObject.code);
});
Initially, the listener is running and -NodeSeverStatus shows Online.
However "after some time" (several hours), the listener is still running fine, and the queue is being processed, but NodeServerStatus now shows Offline.
I could move the online/offline code inside the listener itself, but that would appear to just be an ugly hack, and would presumably still have the same issue if there were no new queue posts within the timeout period.
What is best practice here? Thankyou.
A quick guess is that your network connection gets interrupted briefly.
If you network connection flaps, the server will detect the disconnect and set Offline!.
The client will automatically reconnect, but you never set Online again.
So you'll want to listen for .info/connected and set Online there.
var ref = new Firebase("https://yours.firebaseio.com");
ref.child("NODESERVERONLINE").onDisconnect().set("Offline!");
ref.child(".info/connected").on("value", function(snapshot) {
if (snapshot.val() === true) {
ref.child("NODESERVERONLINE").set("Online");
}
});
See https://www.firebase.com/docs/web/guide/offline-capabilities.html

How to keep a session alive in selenium with phantomjs through nodejs with webdriver.io?

I'm using selenium + phantomjs in a node.js environment through webdriver.io.
For some reason the session ends after a while. Selenium is still up, but in its resource hub, there's no more active session.
How can I prevent this?
Selenium Hub times out any inactive sessions by default in order to free up resources for other requests. You can disable this by setting timeout=0 when starting Hub, either as a command line parameter or through the JSON config depending on how you're starting it.
Keep in mind that if a client crashes with timeouts disabled, that instance will continue to be in-use and won't be available for new sessions.
Sourc: https://code.google.com/p/selenium/wiki/Grid2#Optional_parameters
if you don't want to extend the global timeout to infinity,
you need to execute command before session timeout.
const driverTimeout = 60*1000;
// this interval should run before session expired and keep it alive.
const handleNumber = setInterval(() -> driver.getOrientation(), driverTimeout - 1000);
/** do some long async logic **/
// then stop the interval
clearInterval(handleNumber);
see more about this
https://l18.me/how-to-keep-alive-appium-driver-da9227b2fa

Node: Distinguish between a reload event and a browser exit with socket event

I want to run some code when a a socket is closed but only if the user didn't reload the page...
I have something like
socket.on("close", function() {
//do something here
});
The problem is that this function runs during a reload event as well...Can I somehow pause it to run at a later time with the value at that later time. I tried just using a set timeout within the callback but couldn't access the socket object anymore from within the callback.
Whats the best way to prevent the function from running if a socket connection is regained shortly after?
the main concept of my thought, is that you can never know that a user is reloading or disconnecting and never come back for 1day or so , there are ways to detect that the browser is navigating away from the website, but cant know (in server side) that it will go to the same address, or different..
Instead if any clients disconnect, of course the disconnect event will be fired to socket.io server for that socket, so taking that in account you can set a Session Variable to false you can say that the player is "disconnected" so when the client of that session "reconnects" aka reloads , the socket.io will fire an "connection" event, BUT reading the session variable you can say that the client has previously disconnected and then connected again. Timestamps could apply to this so a reconnection after 15min would have to load some extra data etc..
So you can try this with sessions (assuming that you use express or something)
sockets.on("connection",function(socket){
if(session.isAReload){
// this is a reconnection
}
socket.set("isAReload",session.isAReload /*defaults to false*/);
});
sockets.on('close',function(){
socket.get('isAReload',function(err,isAReload){
if(isAReload){
// closed after reconnecting
}else{
/*
just closed connection, so next time it will be a "reload" or reconnection
a timer of lets say 30s could run to ensure that the client is reloading
*/
session.isAReload=true;
}
});
})

Nodejs req.sessionID occasionally changes after redirect

I am using nodejs, express and connect-memcaced to handle my sessions. I've made a login script which executes perfectly every time, sets the session data and marks the user as logged in and than redirects him back to the page he logged in from. What happens on occasion (not always) is that after he is redirected and the page loads the cookies sessionID changes and the user is off course not logged in anymore. I have failed finding the reason why this happens and why it doesn't happen every time.
Code snipet of the login function:
DB.getOne('User',{filters:{'primary':{email:req.body.email}}}, function(err,data){
if(data[0] && data[0].active == 1){
var encodedPass = self.encodePass(req.body.pass,req.body.email);
if(encodedPass == data[0].pass){
req.session.pr.user = data[0];
req.session.pr.user.status = true;
res.writeHead(302, {
'Location': goTo
});
res.end();
}
}
});
Looking directly into memcached I can see that this executes perfectly and the data is always saved into memcached under the original sessionID. For some reason the redirect must be changing the sessionID
I often find that this happens to me when I do not notice that I have restarted the development server. Remember that the session cookies are stored in memory, so when the server is restarted, all the sessions will be forgotten and the user will be assigned a new session automatically.

NodeJS HTTPServer takes a long time to close

I'm working on a Zappa app, and I'm currently trying to make a little watch script that stops the server, clears require.cache then re-requires and restarts the server when a file changes, something like:
# watch all dependent files
for file of require.cache
fs.watch file, ->
# attach a handler to 'close'
# -- here's the issue: this takes far too long to trigger
server.on 'close', ->
server = require './server'
server.start()
# log the new server's id
console.log server.id
# stop the current server instance
server.stop()
# clear require's cache
delete require.cache[f] for f of require.cache
I also have a console.log server.id line in my request handler so I can check if the IDs match.
So, what happens is: when I change a dependency, the server stops, a new one starts and the new ID is logged, which is all gravy. However, for a random amount of time after, requests to the server still log the old ID, indicating that the old listener is still attached somehow. Eventually, the listener seems to 'switch over' and the new ID is logged.
Update: it seems this is related to the close event (unsurprisingly) - if I attach a simple console.log 'close' callback to the close event, the ID starts changing after 'close' appears. However, it can take a long time (10s+) for the close event to be fired, why might it take so long?
According to the node.js docs:
server.close()
Stops the server from accepting new connections. See net.Server.close().
So, your server would stop accepting new connections, but it won't actually close (and emit close event) until current connections are closed. My guess is that you have clients connected to it, perhaps with keep-alive requests.
I was searching for the same problem. To give you and others searching for this a solution:
You can close all connections immediately, if this is not a problem in your project. This solves the closing problem for me completly.
app.use((req, res, next) => {
res.setHeader('Connection', 'close');
next();
});

Resources