import webview from '@ohos.web.webview';
/**
* Cookie 管理辅助类。
*
* 在 SDK 加载第一个 Web 组件之前调用 `configure()` 一次以确保 Cookie 持久化能力开启。
*/
export class CookieManagerHelper {
private static configured: boolean = false;
/** 全局配置 Cookie 策略,多次调用幂等。 */
public static configure(): void {
if (CookieManagerHelper.configured) {
return;
}
try {
webview.WebCookieManager.putAcceptCookieEnabled(true);
} catch (_e) {
// ignore
}
CookieManagerHelper.configured = true;
}
/**
* 拉取目标 URL 的 Cookie 字符串(用于下载请求头注入等场景)。
*
* @param url 目标 URL
* @returns Cookie 字符串(`a=b; c=d` 形式),无 Cookie 返回空串
*/
public static fetchCookieFor(url: string): string {
if (url === null || url === undefined || url.length === 0) {
return '';
}
try {
const cookie: string = webview.WebCookieManager.fetchCookieSync(url);
return cookie === null || cookie === undefined ? '' : cookie;
} catch (_e) {
return '';
}
}
/**
* 持久化所有内存中的 Cookie 到磁盘。建议在容器关闭前调用。
*/
public static save(): void {
try {
webview.WebCookieManager.saveCookieAsync();
} catch (_e) {
// 容错忽略
}
}
// ArkTS 类禁止实例化
private constructor() {}
}
|