0
votes

I'm creating a simple webview app using nativescript-vue where there is nothing else in the app except the webview that loads a website fullscreen.

On iOS it works great, I can log in to the website turn the app off and on and I'm still logged in.

On Android, the cookies are not saved and you have to log in again every time you turn the app off.

Any way I can enable cookies in the webview for Android?

2

2 Answers

1
votes

I couldn't make it work with cookies, so I had to switch and use localstorage as a backup for saving tokens instead of cookies.

Here is how my final version looks:

<template>
    <Page>
        <WebView @loadStarted="onLoadStarted"
                 @loaded="onWebViewLoaded"
                 src="https://yoururl.com/"
        />
    </Page>
</template>

<script>
    import { isAndroid } from "tns-core-modules/platform"

    export default {
        methods: {
            onLoadStarted (webargs) {
                if (isAndroid) {
                    const webView = webargs.object;
                    webView.android.getSettings().setDomStorageEnabled(true) // This will enable local storage
                }
            },
            onWebViewLoaded(webargs) { // I use this only to disable the default zoom buttons
                if (isAndroid) {
                    const webView = webargs.object;
                    webView.android.getSettings().setDisplayZoomControls(false)
                    webView.android.getSettings().setBuiltInZoomControls(false)
                }
            },
        }
    };
</script>

Apparently, you should be able to enable cookies doing this (at least for newer SDK users):

webView.on(WebView.loadStartedEvent, (args) => {

      webView.android.getSettings().setAcceptThirdPartyCookies(webView, true)

});

But that didn't work as expected as it seemed like sometimes it would save cookies and sometimes it won't or sometimes it would remove cookies (when you log out) and sometimes not.

I hope this info helps someone as it sure seems there is little to none info about this especially if you aren't much familiar with pure Java Android development.

0
votes

This code should work

const webView = webargs.object;

if (android.os.Build.VERSION.SDK_INT >= 21) {
 android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(webView.android, true);
}