Android - PWA does not open in standalone mode with service worker - android

While developing a Progressive-Web-App the following Problem occurred:
Standalone mode works perfectly without including the service worker - but does NOT work with.
Without Service-Worker a2hs (added to Homescreen) PWA gets correctly started in "standalone"-Mode.
After adding the Service-Worker (a2hs + installed / Web-APK) PWA opens new Tab in new Chrome-Window.
Chrome-PWA-Audit:
login_mobile_tablet.jsf / include service worker:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../serviceWorker.js', {scope: "/application/"})
/* also tried ".", "/", "./" as scope value */
.then(function(registration) {
console.log('Service worker registration successful, scope is: ', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error: ', error);
});
}
</script>
serviceWorker.js:
var cacheName = 'pwa-cache';
// A list of local resources we always want to be cached.
var filesToCache = [
'QS1.xhtml',
'pdf.xhtml',
'QS1.jsf',
'pdf.jsf',
'login_pages/login_mobile_tablet.jsf',
'login_pages/login_mobile_tablet.xhtml'
];
// The install handler takes care of precaching the resources we always need.
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
})
// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
// The fetch handler serves responses for same-origin resources from a cache.
self.addEventListener('fetch', event => {
// Workaround for error:
// TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode
// see: https://stackoverflow.com/questions/48463483/what-causes-a-failed-to-execute-fetch-on-serviceworkerglobalscope-only-if
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin')
return;
event.respondWith(
caches.match(event.request, {ignoreSearch: true})
.then(response => {
return response || fetch(event.request);
})
);
});
manifest.json:
{
"name":"[Hidden]",
"short_name":"[Hidden]",
"start_url":"/application/login_pages/login_mobile_tablet.jsf",
"scope":".",
"display":"standalone",
"background_color":"#4688B8",
"theme_color":"#4688B8",
"orientation":"landscape",
"icons":[
{
"src":"javax.faces.resource/images/icons/qsc_128.png.jsf",
"sizes":"128x128",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_144.png.jsf",
"sizes":"144x144",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_152.png.jsf",
"sizes":"152x152",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_192.png.jsf",
"sizes":"192x192",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_256.png.jsf",
"sizes":"256x256",
"type":"image/png"
},
{
"src":"javax.faces.resource/images/icons/qsc_512.png.jsf",
"sizes":"512x512",
"type":"image/png"
}
]
}
The following questions / answers were considered - but no solution was found:
PWA wont open in standalone mode on android
WebAPK ignores display:standalone flag for PWA running on local network
PWA deployed in node.js running in Standalone mode on Android and iOS

Technical Background
The Moment you add your Service-Worker (along all other PWA-Requirements) your App gets created as an Real PWA - with Web-APK getting installed.
Therefore you also need to use Default-HTTPS-Port 443 - make sure you use a valid HTTPS-Certificate.
Before adding the Service-Worker, this mandatory requirement was missing so your PWA was NOT installed and therefore needed less other requirements to be displayed in "standalone-mode".
It's just a shame that this is nowhere documented... and we had to "find out" for ourselves.
Short-List of Mandatory Requirements for "Installable Web-APK":
(As we could not find a full List, i try to include all Points)
Registered Service-Worker (default-implementation like yours is enough)
manifest.json (yours is valid)
https with valid certificate
https default-port (443, eg. https://yourdomain.com/test/)
... for the rest just check chrome audit tool (HINT: you don't need to pass all requirements - your web-apk should work when switching to https-default-port)

Related

How to handle X-CSRF-TOKEN correctly in an angular-based cordova app?

I have an Angular (v10) WebApp, which handles the X-CSRF-TOKEN cookie correctly as explained in the Angular Guide by using the HttpClientXsrfModule in my imports, i.e.:
// app.module.ts
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
}),
and by setting an relative Path in my services' requests, like:
// some service.ts
public deleteX(x_id: number): Observable<any> {
return this.httpClient.delete(`api/X/${x_id}`);
}
and now, the browser itself handles fetching the token from the server and sending it by each subsequent POST/DELETE/PUT/PATCH request successfully.
However, if I compile the application now to an Android app using cordova, the app sends a request (with x_id=1068) to file:///android_asset/www/api/X/1068.
I can modify my http services to use platform-specific absolute/relative paths easily, such as:
// some service.ts
public deleteX(x_id: number): Observable<any> {
if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
return this.httpClient.delete(`${environment.baseUrl}/api/X/${x_id}`);
} else {
return this.httpClient.delete(`api/X/${x_id}`);
}
}
But then, my request's response from the Android application is
error: "access_denied"
error_description: "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'."
What can I do, to add correct handling of the X-XSRF-TOKEN for my cordova compiled Android app?
I ended up using the cordova-plugin-advanced-http, that is offering a response-cookie-fetching opportunity described here.
I've created a generic-http-service containg generic methods for each of the HTTP methods (GET,HEAD,PATCH,PUT,POST,DELETE), that is first checking for the running platform and then forwarding an adjusted request.
example for generic GET (pseudo-code):
// generic-http-service.ts
public get<T>(url: string, queryParams?: any): Observable<T> {
if (this.cordovaService.platform === CordovaService.PLATFORM_ANDROID) {
// android-specific solution
// 1. adjust params
// 2. set general headers + the XSRF-TOKEN from the previous sendt request
// 3. return Observable(obs) {
// 4. send:
cordova.plugin.http.get(`${environment.baseUrl}/${url}`, adjustedParams, adjustedHeaders,
successResponse => {
// 5. fetch & save XSRF-TOKEN
obs.next(JSON.parse(successResponse.data) as T);
}, errorResponse => {
obs.error(errorResponse);
})
}
} else {
// web-specific solution based on the angular guide
return this.httpClient.get(`${url}`);
}
}
Afterwards I just needed to adjust my services a little bit.

How to redirect to app from WebBrowser in Expo

I am currently working on a project on Android using the Expo client for react native. I am trying to open a webpage using WebBrowser, passing my app development URI to the website. The website basically just redirects to the given URI after 5 seconds. However it never seems to open anything. I've used almost the exact same code as here: https://github.com/expo/examples/tree/master/with-webbrowser-redirect. When I load this project into expo and run, it redirects fine. However, when I copy the code for the website and app into my own project, website opens and displays, but redirect does nothing. It just stays there. Here is the code for opening the browser.
_openBrowserAsync = async () => {
try {
this._addLinkingListener();
let result = await WebBrowser.openBrowserAsync(
'https://wexley-auth.firebaseapp.com/?linkingUri=exp://192.168.1.2:19000'
);
this._removeLinkingListener();
this.setState({ result });
} catch (error) {
alert(error);
console.log(error);
}
};
The linking listener never fires the callback which should dismiss the browser. My app URI should be exp://192.168.1.2:19000 as expo developer tools shows me this when I connect over LAN. Ive also tried using Linking.makeUrl() instead of sending URI in string manually. Neither method works for me. Relevant website code:
document.addEventListener("DOMContentLoaded", function(event) {
var links = document.querySelectorAll('a');
var baseUri='';
// Take the uri from the params
var qs = decodeURIComponent(document.location.search);
if (qs) {
baseUri = qs.split('?linkingUri=')[1];
}
var redirectInterval = setInterval(function() {
var countdown = document.querySelector('.countdown');
var t = parseInt(countdown.innerText, 10);
t -= 1;
if (t === 0) {
clearInterval(redirectInterval);
window.location.href = baseUri;
}
}, 1000);
});
Am I missing a step? Do I need to setup a scheme for opening my app or should this work out of the box? Am I using the wrong URI? I noticed that in the example code, the app.json has the following fields that my app.json doesn't have:
"scheme": "expo.examples.with-webbrowser-redirect",
"platforms": [
"android",
"ios"
]

Ionic3 Opentok session.connect doesn;t work

I'm using ionic3 with cordova-plugin-opentok#3.2.2
My session is created by node.js back end and that returns session ID and token without any issues.
When I use that token to connect to a session, the call never returns (in error hander code) and on my mobile, I see a window on android phone but without any streaming from my camera.
Tried upgrading to 3.4.2 plugin, but then that gives errors on gradle. Looked at many exchanges on stack overflow and the Q&A's on the plugin documentation.
startCall() {
// Get the session ID and Token from the server
this.discussionService.initiateVideoCall({userId:this.selUser._id.toString(),slot:this.slotDetails}).subscribe(callDetails => {
this.callDetails = callDetails;
this.token = this.callDetails.token;
this.sessionId = this.callDetails.sessionId;
//this.startVideoCall();
});
}
startVideoCall() {
this.session = OT.initSession(this.apiKey, this.sessionId);
this.publisher = OT.initPublisher('publisher');
this.session.on({
streamCreated: (event: any) => {
this.session.subscribe(event.stream, 'subscriber');
OT.updateViews();
},
streamDestroyed: (event: any) => {
console.log(`Stream ${event.stream.name} ended because ${event.reason}`);
OT.updateViews();
},
sessionConnected: (event: any) => {
this.session.publish(this.publisher);
}
});
this.session.connect(this.token, (error: any) => {
<<< The line below never gets executed>>>>
if (error) {
console.log(`There was an error connecting to the session ${error}`);
}
});
this.session.publish(this.publisher);
}
TokBox Developer Evangelist here.
Previously, there was an issue with the Cordova OpenTok Plugin because it did not support the error handler for the session.connect method. This was fixed with Release v3.4.3.
If you're unable to upgrade, you can remove the error handler from your implementation and call connect and publish like so:
this.session.on({
sessionConnected: (event: any) => {
this.session.publish(this.publisher);
},
});
this.session.connect(this.token);
However, I highly recommend upgrading so you can verify if there was an error before attempting to publish. If you're unable to upgrade because there is an issue with the plugin, please file it here.

React Native Background Download

I am about to build an app which locally stores multiple MySqlite *.db files. These are used to populate the app with data.
The app should regularly check if there is a newer version for one of these files and, if so, download it and replace the old version of the file.
This update process should happen in the background, while the app is inactive or even closed.
I have seen several plugins, which can be used to execute tasks in the Background (like https://www.npmjs.com/package/react-native-background-task). This could be used to check for updates regularly, but the time limit of 30s on iOS will probably not be enough to download the *.db file. Also, the plugin forces a minimum Android API Version of 21.
My question is: Is it possible to poll for updates in the background AND download them, replacing old files?
I found some useful plugins.
1. react-native-fetch-blob
https://github.com/wkh237/react-native-fetch-blob/wiki/Classes#rnfetchblobconfig
It has IOSBackgroundTask option.
RNFetchBlob
.config({
path : dest_file_path,
IOSBackgroundTask: true,
overwrite: true,
indicator: true,
})
.fetch('GET', download_url, {
//some headers ..
})
.progress( (received, total) => {
console.log('progress : '+ received + ' / ' + total);
})
.then((res) => {
console.log('# The file saved to :', file_path);
})
By the way, it looks doesn't work properly.
Not sure if I miss something...
2. react-native-fs
https://github.com/itinance/react-native-fs#downloadfileoptions-downloadfileoptions--jobid-number-promise-promisedownloadresult-
const ret = RNFS.downloadFile({
fromUrl: download_url,
toFile: dest_file_path,
connectionTimeout: 1000 * 10,
background: true,
discretionary: true,
progressDivider: 1,
resumable: (res) => {
console.log("# resumable :", res);
},
begin: (res) => {
// start event
},
progress: (data) => {
const percentage = ((100 * data.bytesWritten) / data.contentLength) | 0;
console.log("# percentage :", percentage);
},
});
jobId = ret.jobId;
ret.promise.then((res) => {
console.log('Download finished.');
RNFS.completeHandlerIOS(jobId);
jobId = -1;
}).catch(err => {
console.log('error');
jobId = -1;
});
It looks working well.
By the way, when I try download in background via push notification, it doesn't start download unless I open the app.
Anyone can solve this problem?
For download in the background, the best module I have used was react-native-background-downloader, which have pause, resume and the download percentage.
import RNBackgroundDownloader from 'react-native-background-downloader';
let task = RNBackgroundDownloader.download({
id: 'dbfile',
url: 'https://link-to-db/MySqlite.db'
destination: `${RNBackgroundDownloader.directories.documents}/MySqlite.db`
}).begin((expectedBytes) => {
console.log(`Going to download ${expectedBytes} bytes!`);
}).progress((percent) => {
console.log(`Downloaded: ${percent * 100}%`);
}).done(() => {
console.log('Download is done!');
}).error((error) => {
console.log('Download canceled due to error: ', error);
});
// Pause the task
task.pause();
// Resume after pause
task.resume();
// Cancel the task
task.stop();
This module is also suitable for iOS and you can download multiple files in a row in the background.

Connecting Android Application With CakePhp website

Is it possible to communicate an android Application with cakePhp website and share data? If it is possible, I want to create an application that can login into the website; my doubt is:
How to pass user name and password from our application to cakephp websites login page? Can anybody show me an example program?
How cakephp controller handle this request and respond to this request? Please show me an example program?
(I am a beginner in android and cakephp.)
Quick answer -- YES!
We just finished pushing an Android app to the market place that does this exact thing. Here's how we did it:
1) Download and learn to use Cordova PhoneGap (2.2.0 is the latest version) within Eclipse. This makes the whole thing so much easier with just some HTML and a lot of Javascript.
2) In your JS, create methods that push the login information using AJAX parameters. Example:
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
$("#login").click(function() {
$email = $("#UserEmail").val();
$pass = $("#UserPassword").val();
$.ajax({
url : yourURL + 'api/users/login',
async : false,
data : {
'email' : $email,
'password' : $pass
},
dataType : 'json',
type : 'post',
success : function(result) {
/**
* do your login redirects or
* use localStorage to store your data
* on the phone. Keep in mind the limitations of
* per domain localStorage of 5MB
*/
// you are officially "logged in"
window.location.href = "yourUrl.html";
return;
},
error : function(xhr, status, err) {
// do your stuff when the login fails
}
});
}
}
3) In Cake / PHP, your Users controller here will take the username and password data in the AJAX call and use that for its authentication.
<?php
class UsersController extends AppController {
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('api_login');
}
public function api_login() {
$this->autoRender = false;
if ($this->request->data && isset($this->request->data['email']) && isset($this->request->data['password'])) {
$arrUser = $this->User->find('all',array(
'conditions'=>array(
'email'=> $this->request->data['email'],
'password' => $this->Auth->password($this->request->data['password']),
)
)
);
if (count($arrUser) > 0) {
$this->Session->write('Auth.User',$arrUser[0]['User']);
// Do your login functions
$arrReturn['status'] = 'SUCCESS';
$arrReturn['data'] = array( 'loginSuccess' => 1,'user_id' => $arrUser[0]['User']['id'] );
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
} else {
$arrReturn['status'] = 'NOTLOGGEDIN';
$arrReturn['data'] = array( 'loginSuccess' => 0 );
}
echo json_encode($arrReturn);
}
}
?>
That's pretty much it. You are now authenticated to CakePHP.
You do not need to use "api_", you can use any function name you want, but this helped us keep a handle on what we allowed mobile users to do versus web users.
Now, these are just the building blocks. You basically have to create a whole version of your site on the phone using HTML and Javascript, so depending on your application it may be easier just to create a responsive design to your site and allow mobile browsing.
HTH!
Use Admad JWT Auth Plugin
If you use cakephp3 change your login function with this one :
public function token() {
$user = $this->Auth->identify();
if (!$user) {
throw new UnauthorizedException('Invalid username (email) or password');
}
$this->set([
'success' => true,
'data' => [
'token' => JWT::encode([
'sub' => $user['id'],
'exp' => time() + 604800
],
Security::salt())
],
'_serialize' => ['success', 'data']
]);
}
You can read this tutorial about REST Api and JWT Auth Implementation
http://www.bravo-kernel.com/2015/04/how-to-add-jwt-authentication-to-a-cakephp-3-rest-api/
if rebuild most of the view pages in cakephp into ajax will seem defeat the purposes of using cakephp as it is.

Categories

Resources