gpt4 book ai didi

javascript - Cookie 未存储在 Android Webview 中

转载 作者:行者123 更新时间:2023-12-02 13:00:19 25 4
gpt4 key购买 nike

我有一个纯 HTML+CSS+JS 应用程序,我正在尝试使用 Webview 将其嵌入到 Android 应用程序中。该应用程序一切正常,只是不存储 cookie。我已经尝试过这些 QA 中的建议,但似乎都不起作用:

Make Android WebView not store cookies or passwords

Cookie doesn't work properly in webview in android

Webview cannot accept cookies

Android WebView HTTP Cookies not working in API 21

这是我在 Activity 中启动 WebView 的方式:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
cookieManager.setAcceptFileSchemeCookies(true);

WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);

//webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowContentAccess(true);
if (Build.VERSION.SDK_INT >= 16) {
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}

webView.loadUrl("file:///android_asset/index.html");

}

下面是 JavaScript createCookie() 方法,可以在普通浏览器中完美运行:

function createCookie(name, value, days) 
{
value = value.replace(';', COOKIE_ENCODER);

if (days>=0) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
//else var expires = "";


document.cookie = name + "=" + value + expires; // + "; path=/";
}

我也尝试过使用 CookieSyncManager,尽管 Android Studio 建议其贬值。调用 createCookie() 方法时,控制台不会显示任何错误,它只是不存储 cookie。

编辑

下面是 readCookie() 函数的代码,用于在 JavaScript 中读取 cookie。我认为同样有可能存储 cookie,但浏览器在读回它时遇到问题:

function readCookie(name) 
{
//name = name.replace(';',COOKIE_ENCODER);
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
{
s = c.substring(nameEQ.length, c.length);
s = s.replace(COOKIE_ENCODER,';');
return s;
}
}
return null;
}

最佳答案

您可以使用 window.localStorage 代替 cookie。 https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

关于javascript - Cookie 未存储在 Android Webview 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44324373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com