Nativescript-vue在Android上保存Cookie

时间:2020-01-29 11:18:04

标签: android webview android-webview nativescript nativescript-vue

我正在使用nativescript-vue创建一个简单的Webview应用程序,除了加载全屏网站的Webview之外,该应用程序中没有其他内容。

在iOS上,它运行良好,我可以登录该网站,然后关闭然后再打开该应用,然后我仍然登录。

在Android上,不会保存cookie,并且每次关闭应用程序时都必须重新登录。

我可以在Android的Web视图中启用Cookie吗?

2 个答案:

答案 0 :(得分:1)

我无法使其与cookie一起使用,因此我不得不切换并使用localstorage作为备份来保存令牌而不是cookie。

这是我最终版本的外观:

<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>

显然,您应该能够启用Cookie(至少对于新的SDK用户而言):

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

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

});

但是这并没有按预期的那样工作,因为有时它会保存cookie,有时却不会,或者有时会删除cookie(当您注销时),有时却不会。

我希望此信息对某人有帮助,因为肯定会发现几乎没有这方面的信息,尤其是如果您对纯Java Android开发不太熟悉的话。

答案 1 :(得分:0)

此代码应该有效

const webView = webargs.object;

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