window.onbeforeunload doesn't trigger on Android Chrome [alt. solution?] - javascript

I have developed a simple chat application where I am using the $window.onbeforeunload to notify other users when somebody closes the tab/browser (basically when the user leaves the room).
Here is my code
$scope.onExit = function() {
$scope.chatstatus.$add({
status: $scope.getUsername + ' left'
});
};
$window.onbeforeunload = $scope.onExit;
This is working absolutely fine on desktop browsers but not on the Android Chrome browser. The onbeforeunload function is not getting triggered at all.
Please suggest a solution/workaround. Thanks.
EDIT: As mentioned in the comments that it is a known issue, kindly suggest a workaround if not the solution.

Looks like you need to check for both onbeforeunload and onunload.
This answer looks like a good way to do that.
Android Chrome window.onunload
window.onunload = window.onbeforeunload = function() {
var guid = sessionStorage.getItem("WindowGUID");
var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
tmp = tmp.remove(guid); // remove is a custom prototype fn
localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
});

Related

Struggling with onclick in mobile browser

I work for a hire company, and I decided paperwork was a pain and have started putting it online instead. I'm building a service/repair database to store records and information on machines on our fleet. We have a desktop pc in the workshop, connected to the internet, but we have had an ongoing issue with our phone lines dropping in and out for the last few years and despite us calling out engineers, they can't explain it. Anyway, long story short, I've made a 'backup' copy of the website and database on localhost using xampp. I made a simple script to detect if we were online or not and added it to an onclick event.
function conchecklink(link) {
var online = navigator.onLine;
var livelink = "http://www.example.com/workshop/" + link;
var locallink = "http://localhost/workshop/" + link;
if (online == true) {
window.location(livelink);
}
if (online == false) {
window.location(locallink);
}
}
For each href on the website I am using this:
<a onclick=\"conchecklink('service.php')\" href=\"#\"> Service</a>
<a onclick=\"conchecklink('repair.php')\" href=\"#\"> Repairs</a>
Now this works absolutely fine on desktop, when internet drops out, it redirects to localhost, and visa versa. But when viewing on my mobile, the onclick event doesn't fire. From googling this, I understand I should be using ontouch for mobile, I tried a few things I found in my search, but alas I am only a mechanic, not a professional coder and I can't get the links working on mobile. Any help would be much appreciated.
You have an error: window.location is not a function. On your mobile, the browser should throw an error and stops the script. Your desktop browser seems to be more conciliant.
You also could use else instead of using two if statements.
function conchecklink(link) {
var online = navigator.onLine;
var livelink = "http://www.example.com/workshop/" + link;
var locallink = "http://localhost/workshop/" + link;
if (online) window.location.href = livelink;
else window.location.href = locallink;
}
The way you have used window.location is wrong, it is not a function hence do not accept arguments.
you can use it like this window.location = URL;

KIll user session on window.onunload

I want to kill a users session if they back out of a certain page.
The problem is apparently window.onunload does not work in chrome or something to that effect. Is there a work around for this where I can kill the session ONLY when the user backs out ? Right now if the user backs out, it will give them a prompt which offers them the choice of staying on the page or leaving.
client side:
<a4j:jsFunction
name="killUserSession"
action="#{sessionController.invalidateSession()}"/>
...........
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have not filled out the required information below.";
}
}
window.onunload = function(){
killUserSession();
}
function setOnloadNull(){
console.log("Setting onload to null");
var warning = false;
window.onbeforeunload = null;
}
I check your issue and i found (under chrome) setOnLoadNull is the cause of the issue.
Demo fails.
But when i disable this method, then the onunload works like a charm.
Demo works.

Android Chrome window.onunload

I am developing an HTML5 app specifically for Android and Chrome. The problem I have stems from the requirement to track open browser tabs. I do this by creating a unique ID stored in each tab's sessionStorage. I then track the open tabs by registering each ID in a localStorage array that each tab has access to.
The problem is that I cannot remove the ID from localStorage when closing a tab by using the window.onunload event. The code works fine in desktop Chrome but I cannot get it working in Android.
$(window).on('beforeunload', function () {
removeWindowGUID();
});
function removeWindowGUID() {
var guid = sessionStorage.getItem("WindowGUID");
var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
tmp = tmp.remove(guid); // remove is a custom prototype fn
localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
}
This event will fire when reloading a page, which is fine, just not on closing.
I have also tried using the pagehide event.
Depends on the browser. Some use .onunload, some use onbeforeunload.
Quickest solution is
window.onunload = window.onbeforeunload = function() {
var guid = sessionStorage.getItem("WindowGUID");
var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
tmp = tmp.remove(guid); // remove is a custom prototype fn
localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
});
Tested on gingerbread, ICS & jelly bean using native android browser.
I did something similar, the errors were exactly the same. I noticed if call window.close() programmatically, the event is called. I just added my own 'close' button on the page.

How can I load a new page when the iPhone/Android browser is reopened?

Okay, so I don't exactly even know how to word this question properly as you can probably tell. Hence I couldn't find any solution on Google, so I came here.
Basically, the process unfolds like this:
1.) The user logs into my site.
2.) The user uses my site, then leaves the browser and does whatever else, without killing the browser.
3.) The user opens up the browser again to check my site again.
When 3.) triggers, I want my site to detect that and forward the browser to some other page.
Does this make any sense? If you need clarification, just let me know. I believe there has to be a way to do this with jQuery or maybe just plain JS.
Thanks!
function onBlur() {
document.body.className = 'blurred';
};
function onFocus(){
document.body.className = 'focused';
};
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
Reference: Is there a way to detect if a browser window is not currently active?

help with Firefox extension in multiple windows

I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file:
var serverSocket;
function startServer()
{
var listener =
{
onSocketAccepted : function(socket, transport)
{
try {
var outputString = gBrowser.currentURI.spec + "\n";
var stream = transport.openOutputStream(0,0,0);
stream.write(outputString,outputString.length);
stream.close();
} catch(ex2){ dump("::"+ex2); }
},
onStopListening : function(socket, status){}
};
try {
serverSocket = Components.classes["#mozilla.org/network/server-socket;1"]
.createInstance(Components.interfaces.nsIServerSocket);
serverSocket.init(7055,true,-1);
serverSocket.asyncListen(listener);
} catch(ex){ dump(ex); }
document.getElementById("status").value = "Started";
}
function stopServer ()
{
if (serverSocket)
serverSocket.close();
}
window.addEventListener("load", function() { startServer(); }, false);
window.addEventListener("unload", function() { stopServer(); }, false);
As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?
Firefox extension overlays bind to window objects. One way around this is to create an XPCOM component or find one that someone else already created to allow you to build functionality without binding it to the window objects.
Of course, section #2 below on Observer Notifications may be helpful as well.
Possible workaround: #1
Instead of calling "startServer()" each time a window is opened, you could have a flag called windowCount that you could increment each time you open a new window. If windowCount is greater than 0, don't call startServer().
As windows close, you could decrement the count. Once it hits 0, stop the server.
Here is information from the Mozilla forums on this problem:
http://forums.mozillazine.org/viewtopic.php?f=19&t=2030279
Possible workaround #2:
With that said, I've also found documentation for Observer Notifications, which may be helpful as there is a section on Application Startup and Shutdown:
https://developer.mozilla.org/en/Observer_Notifications
UPDATE:
Here are some resources on creating XPCOM components in JavaScript and in C++:
https://developer.mozilla.org/en/how_to_build_an_xpcom_component_in_javascript
http://www.codeproject.com/KB/miscctrl/XPCOM_Creation.aspx
https://developer.mozilla.org/en/creating_xpcom_components
You probably want to:
Move your code into a JavaScript component
Register your component as a profile-after-change observer
Whenever someone makes a connection to your socket, find the active window and return its URL.
Use something like
var wm = Components.classes["#mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
var spec = win ? win.getBrowser().currentURI.spec : "";
var outputString = spec + "\n";
etc.

Categories

Resources