cookie.uts 1.9 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2
import webview from '@ohos.web.webview';

DCloud-yyl's avatar
DCloud-yyl 已提交
3 4 5 6 7
// 鸿蒙非secure cookie无法保存
function replaceHttpWithHttps(url: string): string {
    return url.replace(/^http:/, 'https:');
}

DCloud-yyl's avatar
DCloud-yyl 已提交
8
export function getCookie(url: string): Promise<string> {
DCloud-yyl's avatar
DCloud-yyl 已提交
9
    return webview.WebCookieManager.fetchCookie(replaceHttpWithHttps(url));
DCloud-yyl's avatar
DCloud-yyl 已提交
10 11 12
}

export function getCookieSync(url: string): string {
DCloud-yyl's avatar
DCloud-yyl 已提交
13
    return webview.WebCookieManager.fetchCookieSync(replaceHttpWithHttps(url));
DCloud-yyl's avatar
DCloud-yyl 已提交
14 15 16
}

export function setCookie(url: string, cookies: string[]): Promise<void> {
DCloud-yyl's avatar
DCloud-yyl 已提交
17
    return Promise.all(cookies.map(cookie => webview.WebCookieManager.configCookie(replaceHttpWithHttps(url), cookie))).then(() => {
DCloud-yyl's avatar
DCloud-yyl 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
        return webview.WebCookieManager.saveCookieAsync();
    });
}

export function setCookieSync(url: string, cookies: string[]): void {
    cookies.forEach(cookie => {
        let hasSecure = false;
        let hasSameSite = false;
        let savedCookie = cookie.split(';').map(cookieItem => {
            const pair = cookieItem.split('=').map(item => item.trim())
            const keyLower = pair[0].toLowerCase();
            if (keyLower === 'secure') {
                hasSecure = true;
                return cookieItem;
            }
            if (keyLower === 'samesite') {
                hasSameSite = true;
                return 'samesite=none';
            }
            return cookieItem
        }).join(';');
        if (!hasSecure) {
            savedCookie += '; secure';
        }
        if (!hasSameSite) {
            savedCookie += '; samesite=none';
        }
DCloud-yyl's avatar
DCloud-yyl 已提交
45 46 47 48
        try {
            // https://baidu.com/ 会返回一条 Set-Cookie: __bsi=; max-age=3600; domain=m.baidu.com; path=/(无重定向) m.baidu.com与baidu.com不一致configCookieSync会抛出错误导致崩溃
            webview.WebCookieManager.configCookieSync(replaceHttpWithHttps(url), savedCookie);
        } catch (error) { }
DCloud-yyl's avatar
DCloud-yyl 已提交
49 50 51 52
    });
    webview.WebCookieManager.saveCookieAsync();
}