WebComponentUtil.ets 1.66 KB
import bundleManager from '@ohos.bundle.bundleManager';
import web_webview from '@ohos.web.webview';
import HashMap from '@ohos.util.HashMap';
import { StringUtils, AppUtils } from 'wdKit';

/**
 * 用于底层webview基础设置:ua,cookie等
 */
export function setDefaultNativeWebSettings(control: WebviewController, url: string): Promise<void> {
  //设置UA
  let customUA = control.getCustomUserAgent();
    return new Promise((resolve) => {
      let versionName = AppUtils.getAppVersionName();
      let versionCode = AppUtils.getAppVersionCode();
      //TODO 设置cookie有问题
      if(customUA.indexOf('miguvideo')===-1){
        let temp = customUA + " Migu/miguvideo/" + versionName + "(" + versionCode + ")"
        control.setCustomUserAgent(temp)
      }else{
        control.setCustomUserAgent(customUA)
      }
      //设置Cookie
      try{
        syncCookies(url, getBaseCookie())
        web_webview.WebCookieManager.setCookie(url, "AppVersion=" + versionCode)
      }catch(e){
      }
      resolve();
    });
}

function setCookie(url: string, value: string) {
  if (StringUtils.isEmpty(value) || StringUtils.isEmpty(url) || !value.includes("=")) {
    return
  }
  web_webview.WebCookieManager.setCookie(url, value)
}

function getBaseCookie(): HashMap<string, string> {
  let cookies: HashMap<string, string> = new HashMap<string, string>()
  cookies.set("SupportAPI", "H5_CALL_NATIVE_HTTP_REQUEST")
  cookies.set("PlatForm", "harmony")
  return cookies

}

function syncCookies(url: string, map: HashMap<String, String>) {
  if (map == undefined && StringUtils.isEmpty(url)) {
    return
  }
  map.forEach((value, key) => {
    setCookie(url, `${key}=${value}`)
  })
}