目录

How do I synchronize cookies requested from the network to the web page?

The obtained cookie can be set synchronously or asynchronously by using configCookieSync and configCookie provided by Class (WebCookieManager). In this way, the requested cookie is synchronized to the web page.

import { webview } from '@kit.ArkWeb'
@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  headers : Array<webview.WebHeader> = [{ headerKey : "msg",headerValue : 'hello'}];
  build() {
    Column() {
      Button('configCookieSync')
        .onClick(() => {
          try {
            webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b;c=d;e=f');
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      Button('fetchCookieSync')
        .onClick(() => {
          try {
            let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com');
            console.log("fetchCookieSync cookie = " + value);
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      Column() {
        Web({ src: 'www.example.com', controller: this.controller })
          .width('100%')
          .height('100%')
      }
      .layoutWeight(1)
    }
  }
}