Problem with service worker JavaScript on mobile browsers - javascript

This is driving me crazy. I have been trying to implement push notifications for a website and I found a solution (Javacript API notification). The thing is: notifications are not working on mobile devices.
I read about service workers and I have been using this code to ask user for permission and everything, but it is still not working. I am not sure if I am doing something wrong or what. I read about it has to be an https site, but that's does not seem to be the problem. I have also tried the push.js plugin plugin.js, but no succeed so far (even when the demo of that plugin that it's in their website is working on my mobile browser) This is the website >>> https://park-inside.nl/test/
The "Set notification" button is meant to show a notification when the waiting time is below the selected time. So, to test this, just click "Set notification", then select minutes greater than the "Wachttijd" column and refresh page. The notification should appear. It works on desktop browser, but not on mobile. Any idea or suggestion? I would love and appreciate any help.
Note: I am using Chrome 94 on Android 9 (go)
Code that ask for user permission:
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('Notification with ServiceWorker');
});
}
});

See the browser support table for Web Notifications: https://caniuse.com/notifications.
They only work in Chrome on Android, not in the stock Android Browser.
Also, be sure to register a service worker, even if it's an empty one, as seen here: https://stackoverflow.com/a/31787926/10551293.
A demo of the notifications is available here: https://serviceworke.rs/push-payload_demo.html.
Google also has a step-by-step codelab available here: https://developers.google.com/codelabs/pwa-training/pwa03--going-offline#0

Apparently, I had to first do this to register a service worker:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js');
}
I am not really sure, but I was trying to use a route for the sw.js file, like this: js/sw.js. Once I placed that file in the root of the project, it worked.
Also, I added this code to that file to log some events to the console:
self.addEventListener('install', (event) => {
console.log('Installed');
});
self.addEventListener('activate', (event) => {
console.log('Activated');
});
self.addEventListener('fetch', (event) => {
console.log('Fetch request');
});
Thanks to swift-lynx for the links to some documentation, where I found a solution:
https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications

Related

Why is Service worker not working in Chrome?

I am new to web development so sorry if I'm not clear with my question.
I am trying to make a PWA and am currently testing to see if my manifest and service worker are working. In my project, I have an index.html file which calls the file app.js, in which I try to register the service worker named serviceworker.js. Here is the segment of code where I try to register my service worker:
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js')
.then(function() {
console.log('service worker registered');
});
}
else {
console.log('cannot register');
}
When I reload my page, my console displays "cannot register". To troubleshoot this, I wrote a line in the if clause to see if it was a problem with the condition itself. Turns out, Even by removing the if and else clauses and simply running the navigator.serviceWorker.register('/serviceworker.js')
.then(function() {
console.log('service worker registered');
});
segment of the code, the console displays an error say "cannot find property register". From what I understand, service workers do not work on all browsers, but I checked to see if it runs in Chrome (which is what I'm testing in) and it says that service workers are supported. Can someone please tell me why it isn't working? I'm currently using Version 80.0.3987.149 (Official Build) (64-bit) of Chrome. Alsi, I don't know if this is important, but I am using Node.js. Thanks in advance.
Cannot comment because of low reputation, but check this & this out.
In short:
Service workers requires the site using them to be served over HTTPS for security reasons,
but have execptions for localhost.
Check this for how to serve your html file on localhost.

Service Worker Install fails: "cannot read property 'addAll of undefined"

So I'll keep this succinct: When trying to install, my service worker fails. This is all of my code in sw.js:
var cacheName = 'randomstring';
var filesToCache = [ '/' ];
self.addEventListener('install', function (e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName)
.then(function (cache) {
console.log('[ServiceWorker] About to fail');
return cache.addAll(filesToCache);
})
);
});
I get an exception because cache is undefined (on the cache.addAll bit).
Not really sure why this is the case?
I've used service workers before and never encountered this issue. This is my first time using a service worker with an ASP.Net back-end though, so not sure if that's the problem?
So, I figured this out. I was going to vote to close the question, but I figured I'd leave it here as I saw some other people with this issue who didn't know how to resolve it. Even though it's super-stupid :) (or more accurately, I am).
So I was running the website via the "Play" button, aka "Start Debugging", which, in Visual Studio 2017, launches a special Chrome window, in which the above error will be thrown.
To work around the issue, I can (or you can, internet traveller of the future) simply start without debugging, host the website in IIS, etc.
EDIT: If there's a better workaround where I can use the service worker in debug mode, please suggest it and I'll mark that as the answer. For my specific problem though, the above workaround is fine :).
Encountered the same problem and found some other ways.
VS recognises "chrome.exe" while debugging and adds some parameters, that´s why service workers won´t working.
There is an option Debug => Option => Debugging => General => Enable javascript debugging for asp.net (Chrome, Edge and FireFox). If you don´t want to use js debugging in vs - like me because i use chrome for js debugging - just deactivate this option and service workers will work.
VS Enable JS Debugging in Chrome
Alternatively you can add chrome as a new "browser" and switch the browser for debugging. Because vs recognise "chrome.exe" make a symlink via administative commandline "mklink chromedirect.exe chrome.exe" and add it as new browser in visual studio.
This can be done under the "Play" context menu => Browse with.
VS Play Context Menu
Just add chromedirect.exe without any arguments and a friendly name like "Google Chrome Direct". After that you can switch to the browsers and select if you want VS JS Debugging or not.

Using branch.io to redirect to app in javascript

So, we have a mobile download site that we want to bypass if the user already has our app installed, and open our app. We are using the branch javascript code to try to accomplish this task. We have our branch key where I have 'my_branch_key', and we copied the rest of the code below directly out of the branch instructions. And, of course, it is failing to redirect our mobile users. I imagine the problem is the lack of some sort of app identifier in the code, but we could not find any instructions on where to add that. Anyone know what we're missing and where we need to add it. Any advice would be greatly appreciated.
// load the Branch SDK file
(function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode banner closeBanner creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setIdentity track validateCode".split(" "), 0);
branch.init('my_branch_key');
// define the deepview structure
branch.deepview(
{
'channel': 'mobile_web',
'feature': 'deepview',
data : {
'source': 'website'
}
},
{
'open_app': true
}
);
Additional info: We noticed an oddity when trying to test this, for a couple of our iPhone users, it seems to work perfectly, but for the rest of the iPhone users and all the android users it still fails to redirect.
Alex with Branch.io here: the automatic open_app: true setting actually doesn't work in iOS 9 with Safari, due to some changes Apple made to Universal Links in iOS 9.3. This is a fairly recent change, so our docs haven't been updated quite yet. It's annoying, I agree...
The best workaround is to put a button on the page with deepviewCta(). Visitors will have to click it to open the app. We realise this is not ideal, but it's the best option for Apple's current system.
The other option you can try is enabling your own domain for Universal Link. That way whenever a URL at your domain is clicked, your app will launch immediately and the site will never even be loaded.

IOS Cordova Push Plugin - Coldstart Crashes App

I am using the the Cordova Push Plugin: http://ngcordova.com/docs/plugins/pushNotifications/
This works fine in Android Platform. But, for IOS, I face the following issue:
I register listener for '$cordovaPush:notificationReceived' event as per the documentation and provide the same implementation as given in the documentation in the link above (given below for ease):
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
if (notification.alert) {
navigator.notification.alert(notification.alert);
}
if (notification.sound) {
var snd = new Media(event.sound);
snd.play();
}
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge).then(function(result) {
// Success!
}, function(err) {
// An error occurred. Show a message to the user
});
}
});
There are 3 scenarios:
1. App is running in foreground. In such case, even though the notification arrives (confirmed by log statements), no visible action happens on the device.
I expected the below two statements to execute but they dont.
navigator.notification.alert(notification.alert);
snd.play();
App is running in background. In such case, the statements seem to execute as per expected behaviour.
App is NOT running at all (coldstart). In this case, the notification and sound are played but when user click on notification, the app opens and hangs / crashes.
Has anyone encountered these problems before? What is the best way to solve these? This is only for IOS.
The plugin you are using is deprecated.
i also used it before and there are many issues.
i would reccomend to use the plugin: phonegap-plugin-push
easy to install and will solve your issue
As mentioned by #Nechemya Kanelsky, use the newer version of the push plugin and scenario 1 and 2 will be handled. But with that plugin as well, the 3rd issue still remains, as mentioned here
You can use the fix for 3rd issue, mentioned here

Page Worker - destroy() does not seems to remove the window object

I have a SDK add-on that creates a page worker
events.on(eventTarget, "sandbox", (details, content) => {
var pageWorker = worker.Page({
contentScriptFile: data.url("sandbox.js"),
contentURL: data.url("sandbox.html"),
contentScriptWhen: "end"
});
pageWorker.port.emit("detect-version", content, funcs);
pageWorker.port.on("version-detected", (result) => {
if (result.version) {
events.emit(eventTarget, "result-ready", details, results);
}
});
pageWorker.port.on("done", () => {
pageWorker.destroy();
});
});
As you see on the sandbox event there are some messaging back and forth between the add-on and the page worker
the page worker is created
sends a message: detect-version
listens for version-detected
listens for the done event, calls destroy() on the page worker
I expect the worker.destroy() to remove the object and the background page etc.
This does not seem to happen. If I do a browser session for an hour the browser's memory usage is very high and if I check about:memory in Firefox I see a lot of sandbox.html windows entries which I guess indicates that they are not destroyed.
Does anyone know if this is a bug in 1.14?
or am I doing something wrong here? Other options? I need to have a sandboxed page that can communicate with the add-on and pageworker seems to be the only choice for now.
I see there was a bug fix commited 2013-09-26 in the SDK repo that could relate to this https://github.com/mozilla/addon-sdk/commit/55aeedc69984a2c0df78ddb17cee35a960b1135b
Thank you in advance for any help on this
t.
This still seems to be an issue and I doubt there will be a fix for it. I just came across this and ended up minimizing the side effects by just loading a small static resource at the end of my script:
window.location = "data:text/plain,goodbye";
This way any repeating background requests on the original page will no longer run. Be aware though that this will cause the page worker script to re-evaluate, so you are going to have to check window.location at the top of your script.

Categories