pagehide and/or beforeunload not firing in IOS Chrome, Safari - ios

I'm trying to prompt the user whenever he/she tries to navigate away from the current browser (refresh, close tab and window, clicking back button from the browser). I'm having this issue on IOS mobile that it does not fire pagehide and/or beforeunload.
I'm aware that Safari does not support beforeunload event anymore so I've added an event listener for pagehide with similar logic, and that too does not fire. Code is written in angular.
Approach tried:
// Method decorator, Did not work for both
#Hostlistner(window:pagehide), #Hostlistner(window:beforeunload)
doSomething(event:any){
event.returnValue = true;
return true;
}
// Component host property, Also tried this on beforeunload, did not work for both
#Component({
...
host: "(window:pagehide)" : "doSomething($event)"
})
// Plain javascript, have tried pagehide too, did not work for both
window.onbeforeunload = (event) => {
event.returnValue = true;
return true;
};
//Also tried binding it via addEventListener method of window/document, did not work for both
window.addEventListener('beforeunload', (event) => {
this.log("before unload");
event.returnValue = true;
return true;
});
I have been trying it via stackblitz: https://stackblitz.com/edit/angular-qkezha?file=src%2Fapp%2Fapp.component.ts.
Device use for testing the issue: IPhone 6, IOS 12.1
Issue arise on Mobile IOS both for Chrome and Safari, have not tested it in yet in Firefox but I doubt that it will work on there too. Code works on Android Chrome and Windows Desktop Chrome.
I've been on this for several days now. Searching here and there. Any help or hints is very much appreciated.

Related

ReactJs PWA not updating on iOS

I'm building a ReactJs PWA but I'm having trouble detecting updates on iOS.
On Android everything is working great so I'm wondering if all of this is related to iOS support for PWAs or if my implementation of the service worker is not good.
Here's what I've done so far:
Build process and hosting
My app is built using webpack and hosted on AWS. Most of the files (js/css) are built with some hash in their name, generated from their content. For those which aren't (app manifest, index.html, sw.js), I made sure that AWS serves them with some Cache-Control headers preventing any cache. Everything is served over https.
Service Worker
I kept this one as simple as possible : I didn't add any cache rules except precache for my app-shell:
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);
Service-worker registration
Registration of the service worker occurs in the main ReactJs App component, in the componentDidMount() lifecycle hook:
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW is already up and running
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
} else {
// first service worker registration, do nothing
}
}
};
};
});
}
}
Service worker lifecycle management
According to the Google documentation about service workers, a new version of the service worker should be detected when navigating to an in-scope page. But as a single-page application, there is no hard navigation happening once the app has been loaded.
The workaround I found for this is to hook into react-router and listen for route changes, then manually ask the registered service worker to update itself :
const history = createBrowserHistory(); // from 'history' node package
history.listen(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.getRegistration()
.then((reg) => {
if (!reg) {
return null;
}
reg.update();
});
}
});
Actual behavior
Throwing a bunch of alert() everywhere in the code showed above, this is what I observe :
When opening the pwa for the first time after adding it to the homescreen, the service worker is registered as expected, on Android and iOS
While keeping the app opened, I deploy a new version on AWS. Navigating in the app triggers the manual update thanks to my history listener. The new version is found, installed in the background. Then my snackbar is displayed and I can trigger the switch to the new SW.
Now I close the app and deploy a new version on AWS. When opening the app again :
On Android the update is found immediately as Android reloads the page
iOS does not, so I need to navigate within the app for my history listener to trigger the search for an update. When doing so, the update is found
After this, for both OS, my snackbar is displayed and I can trigger the switch to the new SW
Now I close the app and turn off the phones. After deploying a new version, I start them again and open the app :
On Android, just like before, the page is reloaded which detects the update, then the snackbar is displayed, etc..
On iOS, I navigate within the app and my listener triggers the search for an update. But this time, the new version is never found and my onupdatefound event handler is never triggered
Reading this post on Medium from Maximiliano Firtman, it seems that iOS 12.2 has brought a new lifecycle for PWAs. According to him, when the app stays idle for a long time or during a reboot of the device, the app state is killed, as well as the page.
I'm wondering if this could be the root cause of my problem here, but I was not able to find anyone having the same trouble so far.
So after a lot of digging and investigation, I finally found out what was my problem.
From what I was able to observe, I think there is a little difference in the way Android and iOS handle PWAs lifecycle, as well as service workers.
On Android, when starting the app after a reboot, it looks like starting the app and searching an update of the service worker (thanks to the hard navigation occuring when reloading the page) are 2 tasks done in parallel. By doing that, the app have enough time to subscribe to the already existing service worker and define a onupdatefound() handler before the new version of the service worker is found.
On the other hand with iOS, it seems that when you start the app after a reboot of the device (or after not using it for a long period, see Medium article linked in the main topic), iOS triggers the search for an update before starting your app. And if an update is found, it will be installed and and enter its 'waiting' status before the app is actually started. This is probably what happens when the splashscreen is displayed...
So in the end, when your app finally starts and you subscribe to the already existing service worker to define your onupdatefound() handler, the update has already been installed and is waiting to take control of the clients.
So here is my final code to register the service worker :
componentDidMount() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then((reg) => {
if (reg.waiting) {
// a new version is already waiting to take control
this.newWorker = reg.waiting;
/*
code omitted: displays a snackbar to the user to manually trigger
activation of the new SW. This will be done by calling skipWaiting()
then reloading the page
*/
}
// handler for updates occuring while the app is running, either actively or in the background
reg.onupdatefound = () => {
this.newWorker = reg.installing;
this.newWorker.onstatechange = () => {
if (this.newWorker.state === 'installed') {
if (reg.active) {
// a version of the SW already has control over the app
/*
same code omitted
*/
} else {
// very first service worker registration, do nothing
}
}
};
};
});
}
}
Note :
I also got rid of my listener on history that I used to trigger the search for an update on every route change, as it seemed overkill.
Now I rely on the Page Visibility API to trigger this search every time the app gets the focus :
// this function is called in the service worker registration promise, providing the ServiceWorkerRegistration instance
const registerPwaOpeningHandler = (reg) => {
let hidden;
let visibilityChange;
if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
window.document.addEventListener(visibilityChange, () => {
if (!document[hidden]) {
// manually force detection of a potential update when the pwa is opened
reg.update();
}
});
return reg;
};
As noted by Speckles (thanks for saving me the headache), iOS installs the new SW before launching the app. So the SW doesn't get a chance to catch the 'installing' state.
Work-around: check if the registration is in the waiting state then handle it.
I've made an (untested) example of handling this. - a mod to the default CRA SW.

Any way yet to auto-update (or just clear the cache on) a PWA on iOS?

I have been struggling on iOS with something that works easily on Android: Getting my PWA to auto-update when there is a new version. I am not at all sure this is even possible on iOS. I have used vue.js and Quasar to build my app, and everything works out of the box on Android. Here is the (ugly, terrible) way things stand currently on the iOS version:
I can check my own server for the version and compare it against the current one stored in my app (in indexedDB) and throw up a notice that there is a new version. So far so good.
Other than having the user MANUALLY CLEAR THE SAFARI CACHE (!!) there is no way I can figure out how to programmatically clear the PWA cache from within the app or force an upload in another way.
So at this point I guess my questions are:
Has ANYONE been able to get a PWA on iOS (11.3 or later) to auto-update when a new version is available?
Is there a way to clear the (safari) app cache from within my PWA?
Obviously it is an incredibly awful user experience to notify the user that in order to update they must perform several steps outside of the app to be able to refresh it, but it seems this is where iOS stands at the moment unless I am missing something. Has anyone anywhere made this work?
After weeks and weeks of searching, I finally found a solution:
I add a check for versionstring on the server, and return it to the app as mentioned above.
I look for it in localtstorage (IndexedDB) and if I don’t find it, I add it. If I do find it, I compare versions and if there is a newer one on the server, I throw up a dialog.
Dismissing this dialog (my button is labeled “update”) runs window.location.reload(true) and then stores the new versionstring in localstorage
Voila! My app is updated! I can't believe it came down to something this simple, I could not find a solution anywhere. Hope this helps someone else!
UPDATE SEPT 2019:
There were a few problems with the technique above, notably that it was bypassing the PWA service worker mechanisms and that sometimes reload would not immediately load new content (because the current SW would not release the page). I have now a new solution to this that seems to work on all platforms:
function forceSWupdate() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function (registrations) {
for (let registration of registrations) {
registration.update()
}
})
}
}
forceSWupdate()
And inside my serviceworker I now throw up the dialog if there is an update, and do my location.reload(true) from there. This always results in my app being refreshed immediately (with the important caveat that I have added skipWaiting and clientsClaim directives to my registration).
This works on every platform the same, and I can programatically check for the update or wait for the service worker to do it by itself (although the times it checks vary greatly by platform, device, and other unknowable factors. Usually not more than 24 hours though.)
If anyone is still having issues with this, registration.update() did not work for me. I used the exact solution but when the version from my server did not match my local stored version, I had to unregister the service workers for it to work.
if ('serviceWorker' in navigator) {
await this.setState({ loadingMessage: 'Updating Your Experience' })
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.map(r => {
r.unregister()
})
})
await AsyncStorage.setItem('appVersion', this.state.serverAppVersion)
window.location.reload(true)
}
Then when the app reloads, the service worker is reregistered and the current version of the app is visible on iOS safari browsers and 'bookmarked' PWAs.
Instead of prompting the user, that a new version is available, you can also extend the 'activate' Eventlistener to delete your old cache whenever you publish a new serviceworker version.
Add version and name variables
var version = "v3" // increase for new version
var staticCacheName = version + "_pwa-static";
var dynamicCacheName = version + "_pwa-dynamic";
Delete caches, when their names do not fit the current version:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
(credits: https://stackoverflow.com/a/45468998/14678591)
In order to make this work for iOS safari browsers and 'bookmarked' PWAs too, I just added the sligthly reduced function by #jbone107:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
if (!cacheName.startsWith(staticCacheName) &&
!cacheName.startsWith(dynamicCacheName)) {
return true;
}
}).map(function(cacheName) {
// completely deregister for ios to get changes too
console.log('deregistering Serviceworker')
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
registrations.map(r => {
r.unregister()
})
})
window.location.reload(true)
}
console.log('Removing old cache.', cacheName);
return caches.delete(cacheName);
})
);
})
);
});
This way you just have to increase the version number and updating is done by the serviceworker automatically.

How to prevent onBeforeUnload listener in dart from prompting the user?

I basically want just to listen for 'onbeforeunload' to make sure the user won't receive 'connection lost' error messages from my ajax calls. i therefore registered an event and simply set a variable to true that i know to not bother the user with further error messages:
window.onBeforeUnload.listen((BeforeUnloadEvent e){
isUnloading = true;
});
in Dartium this works, after running dart2js i get a javascript alert with 'false':
according to related questions, to set the text I would have to set e.returnValue = 'Prompt'; - but what should i do if I do NOT want to show any dialog? - according to the MDN the prompt is shown for every non-void return value.. but how can i set returnValue to void? (null is not working) - is this a bug, or am i doing it wrong? (dart sdk 1.0.0.7)
There seems to be no way to prevent this dialog in Chrome if you subscribe to onBeforeUnload.
You can try the onPageHide event (works in Chrome, may not work in other browsers).

Firefox SDK - Detecting back button in extension

I'd like to do the equivalent of chrome.tabs.onUpdated in Firefox. tabs.on('ready', function(tab){}) does not work because it does not detect the back button. How do I fire an action on every page load such that it also detects the back button using the Firefox SDK?
You'd have to use require('window-utils').WindowTracker to all windows, filter for browser windows with the require('sdk/window/utils').isBrowser(window) method, then listen to click events on the back button.
It's currently impossible, but will be possible in a future version of Firefox:
https://github.com/mozilla/addon-sdk/commit/e4ce238090a6e243c542c2b421f5906ef465acd0
A bit of a late answer, but for anyone reading this now (from 2016), it is now possible to do using the SDK!
Using the High-Level API tabs, you need to listen for the pageshow event. (More about this on MDN)
An example:
tabs.on('pageshow', function(tab) {
// Your code here
})
It is very similar to the load and ready events, the main difference being that is is also fired when a page is loaded from BFCache (which it is when the back button is pressed).
I think the following snippet gives the functionality of chrome.tabs.onUpdated
var tabs = require("sdk/tabs");
tabs.on('ready', function(tab){
console.log(tab.url);
});

PhoneGap navigator.compass.getCurrentHeading called multiple times on iPhone

I would appreciate any help in solving this - or at least where to look to solve it.
What I have is calling on iPhone navigator.compass.getCurrentHeading(succ, fail), the success function is called every time the device is moved even slighly. In the XCode debug log I see lots of entries of navigator.compass.setHeading calls being generated for every movement. If I try to poll for heading data again - the request just hangs. Here's the code:
function onBodyLoad() {
if (typeof navigator.device == "undefined") {
document.addEventListener("deviceready", onDeviceReady, false);
} else {
onDeviceReady();
}
}
function succ(heading) {
alert("compass " + heading);
}
function fail() {
alert('fail');
}
function onDeviceReady() {
navigator.compass.getCurrentHeading(succ, fail);
}
This is really strange behaviour, as I expect getCurrentHeading to be called just once and return a single result, instead of the unstoppable flurry of events.
I use PhoneGap 1.0.0. The same code on Android works perfectly. I've removed all custom JS code to prevent possibility of conflicts.
It is odd that noone else seems to encounter this. In any case, this (hacky) solution may help anyone who comes looking for an answer.
We had to stop using getCurrentHeading because of this issue, and replaced it with navigator.compass.watchHeading instead. On clearing the watch we also call navigator.compass.stop() function to prevent from further compass spamming (for iPhone platform only - Android is fine), and before calling watchHeading again we call navigator.compass.stop() and navigator.compass.start(), to reinitialize the compass "just in case" (again, on iPhone only).
After taking these measures the page that user compass no longer hangs on second entry, and there is no heading spamming outside of this page.

Resources