Service worker not registering on mobile Chrome - javascript

I want to implement push notifications for my domain on desktop and mobile. On desktop everything works as expected and I'm able to send pushes from my server to the test devices.
On Chrome for Android, I'm not even able to register the service worker. I have tested the following code on OnePlus 3 and Huawei Mate 9 which are recent and powerful devices and I actually receive web notifications on them.
This is the code I use:
<script type="text/javascript">
if('serviceWorker' in navigator && 'PushManager' in window) {
alert('best');
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
alert('test');
});
});
}
</script>
The first alert pops so the browser supports service workers and push notifications. The second one for some reason doesn't pop on mobile chrome but works on desktop chrome! Am I missing something?
The code resides on a page called test.php
Thanks!

change "./sw.js". Because if you dont use dot, it means located in root of your server

Try not using ./ before the file name and instead simply using the file name sw.js. I too was having the same issues, maybe this will help

Related

Why is Service Worker not running on Chrome for Android?

Currently I'm trying to build a web app using the Samsung Tab A. I thought this device would support Service Workers, cause following Can I Use says Chrome for Android 55 is required to run SW.
The tablet is running Android 6.0.1 (no more updates available) and Chrome 55.0.2, but unfortunately when the code shown below runs, the 'no sw' alert pops up.. The SW works fine in Chrome on desktop (mac OS).
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then((registration) => {
alert('sw');
console.log('ServiceWorker successful, scope: ', registration.scope);
}).catch((err) => {
alert('no sw');
console.log('ServiceWorker failed: ', err);
});
}
Am I doing something wrong, or is it not possible to run SW on this kind of tablet? What else is needed if Chrome 55 isn't enough? I think there is some lack of information about this topic since I can't find the answer on this .. :(
Thanks in advance!
EDIT: I'd already enable multiple flags via chrome://flags without any success..
I was using ngrok to serve my webapp locally to my tablet. Did forget to use https..
Go to chrome://flags and add the url like http://localhost:3000/ to the unsafe input
if you don't know just follow the picture bellow.
https://i.ibb.co/Tvwv6VN/Screenshot-20220727-223110.jpg
after this re launch your chrome or any browser.

Branch.io Cordova API - init() fails on Android Device

I'm having problems getting Branch.io to work in a Cordova powered Android app. I have a landing page that parses the data from branch.io deep links and forwards the user to the correct page. My javascript for this page contains:
function onDeviceReady() {
console && console.log("Device Ready");
initBranch();
}
function initBranch() {
branch.init(<branchKey>, function(err, data) {
console && console.log("branch init error: " + err);
//then the parsing and forwarding follows - omitted here
}
I then created a Branch.io deep link to this landing page in the web api and tested it in chrome which works.
Then i tried to move to the Cordova app...
I followed this guide to prepare the app for branch.io:
https://dev.branch.io/recipes/quickstart_guide/cordova/ (I installed the plugin and adapted the Manifest file.)
But when i try to open the same link that worked in chrome on my Android device the app opens correctly and the landing page loads, but i'm not forwared. Instead i see the following error in logcat:
I/chromium(19382): [INFO:CONSOLE(22)] "Device Ready"
[...]
I/chromium(19382): [INFO:CONSOLE(29)] "branch init error: Error: API request /v1/open missing parameter device_fingerprint_id"
Can anyone tell me what i'm doing wrong? I'm just getting to know Cordova and Branch.io so it's probably something small i'm overlooking.
Thanks,
Lif
A colleague of mine figured it out:
Branch.io creates an entry branch_session in the local storage of the android device. On my device this session was corrupted somehow and the device_fingerprint_id was empty:
{"session_id":"198413861345316824","identity_id":"198398707320770300","device_fingerprint_id":null,"browser_fingerprint_id":null,"link":"<link>","data":"{\"+is_first_session\":false,\"+clicked_branch_link\":false}"}
After clearing the local storage* the session was freshly created, and now looks like this:
{"session_id":"198413861345316824","identity_id":"198398707320770300","device_fingerprint_id":"118176839880411216","browser_fingerprint_id":null,"link":<link>,"data":"{\"+is_first_session\":false,\"+clicked_branch_link\":false}"}
And now deep linking works.
Kr,
Lif
* To clear the local storage i used chrome://inspect --> inspect webview, go to resources tab, choose "local storage" and the the correct url, then remove all values.

Facebook app browser debugging [duplicate]

I'm developing website with a lot of HTML5 and CSS3 features. I'm also using iframe to embed several content on my website. It works fine if I open it using Chrome/Firefox/Safari mobile browser. However, if I share on facebook (post/page) and I opened it up with Facebook application with Facebook Internal Browser, my website is messed up.
Is there any tools or way to debug on Facebook Browser? Thanks.
This is how you can do the debugging yourself. It's painful, but the only way I've come across so far.
tl;dr Get the Facebook App loading a page on your local server so you can iterate quickly. Then print debug statements directly to the page until you figure out what is going on.
Get a link to a page on your local server that you can access on your mobile device (test in mobile safari that it works). See this to find out your local IP address How do you access a website running on localhost from iPhone browser. It will look something like this
http://192.xxx.1.127:3000/facebook-test
Post that link on your Facebook page (you can make it private so your friends aren't all like WTF?)
Click the posted link in the Facebook mobile App and it will open up in Facebook's mobile browser
Since you don't have a console, you basically need to print debug statements directly to the page so it is visible. Put debug statements all over your code. If your problems are primarily related to CSS, then you can iteratively comment out stuff until you've found the issue(s) or print the relevant CSS attributes using JavaScript. Eg something like (using JQuery)
function debug(str){$('body').append("<br>"+str);}
Quite possibly the most painful part. The Facebook browser caches very aggressively. If you are making changes and nothing has happened, it's because the content is cached. You can sometimes resolve this by updating the URLs, eg /facebook-test-1, /facebook-test-2, or adding dummy parameters eg /facebook-test?dummy=1. But if the changes are in external css or js sheets it sometimes will still cache. To 100% clear the cache, delete the Facebook App from your mobile device and reinstall.
The internal browser the Facebook app uses is essentially a uiWebView. Paul Irish has made a simple iOS app that lets you load any URL into a uiWebView which you then can debug using Safari's Developer Tools.
https://github.com/paulirish/iOS-WebView-App
I found a way how to debug it easier. You will need to install the Ghostlab app (You have a 7-day free trial there, however it's totally worth paying for).
In Ghostlab, add the website address (or a localhost address) you want to debug and start the session.
Ghostlab will generate a link for access.
Copy that link and post it on Facebook (as a private post)
Open the link on mobile and that's it! Ghostlab will identify you once you open that link, and will allow you to debug the page.
For debugging, you will have all the same tools as in the Chrome devtools (how cool is that!). For example, you can tweak CSS and see the changes applied live.
If you want to debug a possible error, you can try to catch it and display it.
Put this at the very top of your code:
window.onerror = function (msg, url, lineNo, columnNo, error) {
var string = msg.toLowerCase();
var substring = "script error";
if (string.indexOf(substring) > -1){
alert('Script Error: See Browser Console for Detail');
} else {
var message = [
'Message: ' + msg,
'URL: ' + url,
'Line: ' + lineNo,
'Column: ' + columnNo,
'Error object: ' + JSON.stringify(error)
].join(' - ');
alert(message);
}
}
(Source: MDN)
This will catch and alert your errors.
Share a link on Facebook (privately), or send yourself a message on Facebook Messenger (easier). To break the cache, create a new URL every time, e.g. by appending a random string to the URL.
Follow the link and see if you can find any errors.
With help of ngrok create temporary http & https adress instead of your ordinary localhost:3000(or other port) and you could run your app on any devices. It is super easy to use.
and as it was written above all other useful information you should write somewhere inside div element (in case of React I recommend to put onClick on that div with force update or other function for getting info, sometimes it helps because JS in FB could be executed erlier than your information appears). Keep in mind that alerts are not reliable, sometimes they are blocked
bonus from ngrok that in console you will see which files was
requested and response code (it will replace lack of network tab)
and about iFrame.If you use it on other domain and you rely on cookies - you should know that facebook in-app browser blocks 3rd party cookies
test on Android and iOS separately because technicaly they use different browsers

Basic Google Sign-In for Websites code not working in Internet Explorer 11

I am attempting to use Google Sign-In for Websites (https://developers.google.com/identity/sign-in/web/) and noticed that my solution is not working in Internet Explorer 11. To try to eliminate as many factors as possible, I created a simple test case based on the sample code provided by Google.
I've tested it in Chrome on my Windows 7 PC, Chrome on my Mac, Safari on my Mac, Firefox on my Mac and Safari on my iPhone. It works on all of these (e.g., when I click the sign in button and select/enter my Google account, it returns to the page and the button says, "Signed in").
It does not, however, work on Internet Explorer 11 on PC or, strangely enough, Chrome for iOS. When the button is clicked, a window opens to allow me to select my Google account, but after making a selection, the window closes and returns to the page with a button that still says, "Sign In."
Here is the sample code:
<html>
<head>
<meta name="google-signin-client_id" content="61023618497-vqfbod57f26ncjl9d6firk3t09ve4tt3.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2"></div>
</body>
</html>
Any ideas as to what might be going on? I've searched around and have not found any solutions.
One idea was to add "accounts.google.com" to IE's Trusted Sites. This didn't work. I also tried accessing the page via https instead of http. That didn't make a difference either. Anything else I should try?
I ran into the same problem now, a few months later.
If you look at:
https://developers.google.com/identity/sign-in/web/build-button
and try a signin with their demo button, it does not work with IE11 (but it works with other browsers I am using at different OS). I could not find any solution.
I am leaving the comment for a future reader, who searches for the same problem in the future. If the demo button at Google does not work, she can at least rest assured that the problem is probably not in her code. :)
Be sure that you don't have IE 11 configured to block all third party cookies.
Third party cookies are required, and the user experience that occurs when third party cookies are blocked--as you've discovered--leaves much to be desired. There is no warning or error message presented to the user.
You could try to catch the error before it happens. It is possible to detect whether or not third party cookies are blocked by trying to set a cookie on a second domain (that you control) and then making a second request to ensure the cookie is set. You'll need a script or something on your server that can set and check for the cookie (it can't be done using only JavaScript because of the browser security model).
I've had success doing the following:
Loading the script to initiate the Google button rendering etc. from $document.ready. (i.e.Whatever you have in the apis.google.com/js/client:platform.js?onload= x )
e.g.
<script src="https://apis.google.com/js/client:platform.js?onload=startApp" async defer></script>
Move startApp() to here:
$(document).ready(function () {
startApp();
Where startApp() looks something like this:
function startApp() {
gapi.load('auth2', function () {
gapi.client.load('plus', 'v1').then(function () {
gapi.signin2.render('signin-button', {
scope: 'https://www.googleapis.com/auth/plus.login',
fetch_basic_profile: false
});
gapi.auth2.init({
fetch_basic_profile: false,
scope: 'https://www.googleapis.com/auth/plus.login'
}).then(
function () {
console.log('init');
auth2 = gapi.auth2.getAuthInstance();
auth2.isSignedIn.listen(updateSignIn);
auth2.then(updateSignIn());
});
});
});
}
I struggled to get the example to work on localhost, but as soon as I deployed it to the real URL, it worked.

Chrome API: Get Window Type

I'm working on a project and run into an issue where I need to distinguish a chrome app window from normal ones. (Specifically I'm using the --app=URL from a bash script) Because of the way things are setup, I have to have run a js script on all windows, but only do something if they are an app window. It seems that the API listed here is what I need to distinguish one window from another, but all I've managed to get are errors saying that a function or object is undefined. So how am I suppose to get the window type from the API with something like window.type?
Additionally, if you know of some other way to tell the difference between chrome windows if they are an app window or not, then that would also work. I really just need to be able to do:
if (window is app) //I don't really care how it's done
{
doSomething();
}
More information:
Tried in both Chrome and Chromium (both fully updated)
Using Ubuntu 18.04
JavaScript is running in the app window and not an extension (not developing an extension)
Can you try the following. In your console
windowType=window.location.host
It should return if you are in app window it will return as "app". Using this you can write your logic
if (windowType === 'app' ) //I don't really care how it's done
{
doSomething();
}
Hope it helps.
Doing windowType.window.location.host returned not the type of window but rather the url provided with the --app=url flag in my bash script. This means that if you open a normal window and go to the same url as provided in the app window, both would return the same url. However, since the normal window would be the same content just a different window type, the JavaScript code that I need to run on the webpage is the same, thus I would want it to run on both windows. So this solution works for me, but for anyone else who is looking for a window specific identifier, and not just a url, I suppose that is still up in the air.
(Thanks Ragavan Rajan)

Categories

Resources