Search code examples
androidsessionpush-notificationphonegapinappbrowser

Phonegap - Push notification with embedded web app (InAppBrowser window)


I am wrapping an existing web app (Rails) as a cordova app in a webview. I am opening the homepage on onDeviceReady. Followed by registering for push notification.

var ref = cordova.InAppBrowser.open(window.app_url, 
                            '_blank', 'location=no,clearsessioncache=no');
setupPushNotifications(window.app_url, ref);

I am using phonegap-plugin-push for push notifications.

push.on('registration', function(data) {
    saveRegistrationId(app_url, data);
});

I would like to associate the notification registrationId in the context of a logged in user in the web app.

This seems to work without a hitch when using the phonegap developer app. But this does not make a call to the rails app to save the registrationId when I install the android-debug.apk on my device.

The content of config.xml

<access origin="*" />
<allow-navigation href="http://192.168.1.3:8000" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />

I have also tried _self, to open in the same webview. It does not run setupPushNotifications.

The code for registering the token

function saveRegistrationId(app_url, data) {
    // this is our payload for the POST request to server
    // data = {registrationId: 'XXXXX', registrationType: 'FCM'}
    const device_data = Object.assign(data, this.device);

    const url = app_url + "/mobile_devices";

    navigator.notification.alert(data.registrationId);

    navigator.notification.alert(url);

    var httpRequest = new XMLHttpRequest();

    httpRequest.open('POST', url);

    httpRequest.onreadystatechange = function() {
        navigator.notification.alert('readyState : ' + httpRequest.readyState);
        navigator.notification.alert('status : ' + httpRequest.status);
        if (httpRequest.readyState>3 && httpRequest.status==200) { console.log(httpRequest.responseText); }
    };

    httpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    httpRequest.setRequestHeader('Content-Type', 'application/json');
    httpRequest.send(JSON.stringify({device: device_data}));
}

Solution

  • The problem was with the content-security-policy in index.html.

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:; connect-src 'self' http://192.168.1.3:8000;">
    

    The key was the last section

    connect-src 'self' http://192.168.1.3:8000;
    

    That allows ajax requests to be made to the web app.