有需求写一个Unity打包WebGL,然后写入Cookie的需求
WebGL本身不支持写入Cookie操作,所有要调用javaScript
在代码完全正确的情况下遇到了浏览器报错,以下两点需要注意
1.jslib文件中,任何中文注释都不要有
2.jslib应当保存为ANSI文件,而不是UTF-8文件
随文附上写入Cookie的代码
mergeInto(LibraryManager.library, {
GetCookie: function(namePtr) {
var name = Pointer_stringify(namePtr);
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) {
var value = c.substring(nameEQ.length, c.length);
return allocateUTF8(value);
}
}
return allocateUTF8("");
},
SetCookie: function(namePtr, valuePtr, days) {
var name = Pointer_stringify(namePtr);
var value = Pointer_stringify(valuePtr);
var expires = "";
if (days > 0) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
},
DeleteCookie: function(namePtr) {
var name = Pointer_stringify(namePtr);
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
});
Unity的代码
using System.Runtime.InteropServices;
using UnityEngine;
public class CookieReader : MonoBehaviour
{
// 导入JS方法(保持声明不变,但现在与JS实现匹配)
[DllImport("__Internal")]
private static extern string GetCookie(string name);
[DllImport("__Internal")]
private static extern void SetCookie(string name, string value, int days);
[DllImport("__Internal")]
private static extern void DeleteCookie(string name);
// 读取指定名称的Cookie
public static string ReadCookie(string name)
{
#if UNITY_WEBGL && !UNITY_EDITOR
return GetCookie(name);
#else
Debug.LogWarning("非WebGL平台无法读取浏览器Cookie");
return "";
#endif
}
// 写入Cookie
public static void WriteCookie(string name, string value, int days = 30)
{
#if UNITY_WEBGL && !UNITY_EDITOR
SetCookie(name, value, days);
#else
Debug.LogWarning($"非WebGL平台无法写入浏览器Cookie,值: {name}={value}");
#endif
}
// 删除Cookie
public static void RemoveCookie(string name)
{
#if UNITY_WEBGL && !UNITY_EDITOR
DeleteCookie(name);
#else
Debug.LogWarning($"非WebGL平台无法删除浏览器Cookie: {name}");
#endif
}
public void WriteCookieTest()
{
// 检查Cookie是否存在
string username = CookieReader.ReadCookie("username");
if (!string.IsNullOrEmpty(username))
{
RemoveCookieTest();
}
else
{
// 写入有效期30天的Cookie
CookieReader.WriteCookie("username", "JohnDoe", 30);
ReadCookieTest();
}
// 写入会话Cookie(浏览器关闭后失效)
CookieReader.WriteCookie("session_id", "123456", -1);
}
public void RemoveCookieTest()
{
// 删除指定Cookie
CookieReader.RemoveCookie("username");
}
public void ReadCookieTest()
{
// 检查Cookie是否存在
string username = CookieReader.ReadCookie("username");
if (!string.IsNullOrEmpty(username))
{
Debug.Log("用户已登录,SessionID: " + username);
}
else
{
Debug.Log("用户未登录");
}
}
}

1345

被折叠的 条评论
为什么被折叠?



