Android Chrome window.onunload - javascript

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.

Related

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

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));
});

Android InAppBrowser _system callbacks

I have been developing a mobile app for Android/IOS/Windows 8 in Cordova that needs to pass a few strings to a web page. Unfortunately for me, the web page does not support TLS 1.0 protocol, which means older Android versions (and IOS versions) cannot open the page within the native browser.
This means the window.open call, when set to '_blank', will not load the page on any Android version before 16 API, and it's only really guaranteed for 19 API and above:
window.open('https://www.libertymountain.com/login.aspx','_blank')
My solution was to change it to "_system" instead of "_blank". This works, because the phone can use the chrome or safari browser instead of the native browser. However, when I do this, all of the callbacks cease to work. It just opens up the page, and I can't run the script on it.
For example, the code below does NOT ever execute the callback. It merely opens the webpage:
var ref = window.open('https://www.libertymountain.com/login.aspx','_system');
ref.addEventListener('loadstart', function() { alert("Hello"); });
Am I missing something, or is there a proper way to do this?
EDIT: Just to make it clear, this is my code that never triggers the callback:
document.addEventListener("deviceready", init, false);
function init() {
window.open = cordova.InAppBrowser.open;
var ref = window.open('https://www.libertymountain.com/login.aspx', '_system');
// This event never triggers, nor does any other event, even though the
// webpage is opened in Chrome
websiteReference.addEventListener('loadstart', function(event) { console.log('Hello'); });
}
If I change it to this, the events do trigger. But I need to do it with '_system' otherwise older Android and IOS devices won't be able to do it.
document.addEventListener("deviceready", init, false);
function init() {
window.open = cordova.InAppBrowser.open;
// Change '_system' to '_blank'
var ref = window.open('https://www.libertymountain.com/login.aspx', '_blank');
// This event never triggers, nor does any other event, even though the
// webpage is opened in Chrome
websiteReference.addEventListener('loadstart', function(event) { console.log('Hello'); });
}
I heard that you can't actually execute scripts or trigger callbacks in the external system browsers (when using the '_system' option for InAppBrowser window.open()). From my testing, this seems to be true. On the other hand, '_blank' does of course trigger callbacks because it is using the native browser within the app.
In order to run script on another file you need to load that file first like this:-
var ref = window.open('http://www.libertymountain.com/','_system');
$(ref .document).load(function() {
alert('Hello');
// do other things
});
OR +-------
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var ref = window.open('http://www.libertymountain.com/','_system');
ref.addEventListener('loadstart', function(event) { alert('Hello'); });
}

Refresh external browser window in node-webkit

I'm trying to load a file in the browser and then refresh it when an event is fired. I'm using the node-open module:
var open = require('open');
var url = 'http://www.stackoverflow.com';
var myWindow = open(url); //returns a child process
myWindow.on('refresh', function() {
open(url);
});
// stuff...
myWindow.emit('refresh');
The open() method returns a child process, so I'm attaching an event listener to it that is triggered when the refresh event is fired. However (as you can see) a new window is opened when refresh is fired. How can I keep track of the original window and refresh it?
If you really mean an external browser, then I'm not sure, but if you're using the window.open in node-wekbit, you could do this:
var url = 'http://www.stackoverflow.com';
var myWindow = open(url); // returns a Window object
. . .
myWindow.window.location.reload();
This will open another node-webkit window with the given url, but beware that it's not as safe to browse with node-webkit as with a standard browser as not all of the security protections are in place.
If you're talking about an external browser, then I'm not sure there is an easy solution. I don't think there's a signal you can send a child process to cause a browser reload.

How can I detect an address bar change with JavaScript?

I have a Ajax heavy application that may have a URL such as
http://example.com/myApp/#page=1
When a user manipulates the site, the address bar can change to something like
http://example.com/myApp/#page=5
without reloading the page.
My problem is the following sequence:
A user bookmarks the first URL.
The user manipulates the application such that the second URL is the current state.
The user clicks on the bookmark created in step 1.
The URL in the address bar changes from http://example.com/myApp/#page=5 to http://example.com/myApp/#page=1, but I don't know of a way to detect the change happened.
If I detect a change some JavaScript would act on it.
HTML5 introduces a hashchange event which allows you to register for notifications of url hash changes without polling for them with a timer.
It it supported by all major browsers (Firefox 3.6, IE8, Chrome, other Webkit-based browsers), but I'd still highly suggest to use a library which handles the event for you - i.e. by using a timer in browsers not supporting the HTML5 event and using the event otherwise.
window.onhashchange = function() {
alert("hashtag changed");
};
For further information on the event, see https://developer.mozilla.org/en/dom/window.onhashchange and http://msdn.microsoft.com/en-us/library/cc288209%28VS.85%29.aspx.
check the current address periodically using setTimeout/interval:
var oldLocation = location.href;
setInterval(function() {
if(location.href != oldLocation) {
// do your action
oldLocation = location.href
}
}, 1000); // check every second
You should extend the location object to expose an event that you can bind to.
ie:
window.location.prototype.changed = function(e){};
(function() //create a scope so 'location' is not global
{
var location = window.location.href;
setInterval(function()
{
if(location != window.location.href)
{
location = window.location.href;
window.location.changed(location);
}
}, 1000);
})();
window.location.changed = function(e)
{
console.log(e);//outputs http://newhref.com
//this is fired when the window changes location
}
SWFaddress is an excellent library for these types of things.

How can I detect changes in location hash?

I am using Ajax and hash for navigation.
Is there a way to check if the window.location.hash changed like this?
http://example.com/blah#123 to http://example.com/blah#456
It works if I check it when the document loads.
But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).
It shows inside the address box, but I can't catch it with JavaScript.
The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.
Update to keep this answer fresh:
If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.
$(window).on('hashchange', function() {
//.. work ..
});
The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.
With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).
In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.
This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.
HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:
Internet Explorer 8
Firefox 3.6
Chrome 5
Safari 5
Opera 10.6
Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.
if (("onhashchange" in window) && !($.browser.msie)) {
window.onhashchange = function () {
alert(window.location.hash);
}
// Or $(window).bind( 'hashchange',function(e) {
// alert(window.location.hash);
// });
}
else {
var prevHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != prevHash) {
prevHash = window.location.hash;
alert(window.location.hash);
}
}, 100);
}
EDIT -
Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/
There are a lot of tricks to deal with History and window.location.hash in IE browsers:
As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.
Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.
However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.
If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)
I know this isn't a real response, but maybe IE-History notes are useful to somebody.
Firefox has had an onhashchange event since 3.6. See window.onhashchange.
I was using this in a react application to make the URL display different parameters depending what view the user was on.
I watched the hash parameter using
window.addEventListener('hashchange', doSomethingWithChangeFunction);
Then
function doSomethingWithChangeFunction () {
let urlParam = window.location.hash; // Get new hash value
// ... Do something with new hash value
};
Worked a treat, works with forward and back browser buttons and also in browser history.
You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.
Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.
The code will look like this:
window.location.watch(
'hash',
function(id,oldVal,newVal){
console.log("the window's hash value has changed from "+oldval+" to "+newVal);
}
);
Then you can test it:
var myHashLink = "home";
window.location = window.location + "#" + myHashLink;
And of course that will trigger your observer function.
Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.
Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!
var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123
function TrackHash() {
if (document.location != page_url + current_url_w_hash) {
window.location = document.location;
}
return false;
}
var RunTabs = setInterval(TrackHash, 200);
That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.
I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.
path.js NPM
path.js GitHub
SHORT and SIMPLE example
Click on buttons to change hash
window.onhashchange = () => console.log(`Hash changed -> ${window.location.hash}`)
<button onclick="window.location.hash=Math.random()">hash to Math.Random</button>
<button onclick="window.location.hash='ABC'">Hash to ABC</button>
<button onclick="window.location.hash='XYZ'">Hash to XYZ</button>

Categories

Resources