鸿蒙应用开发中,使用ArkWeb组件开发页面,如何设置UserAgent?

阅读 694
1 个回答

当Web组件src设置了url时,建议在onControllerAttached回调事件中设置UserAgent,设置方式请参考示例。不建议将UserAgent设置在onLoadIntercept回调事件中,会概率性出现设置失败。如果未在onControllerAttached回调事件中设置UserAgent。再调用setCustomUserAgent方法时,可能会出现加载的页面与实际设置UserAgent不符的异常现象。

当Web组件src设置为空字符串时,建议先调用setCustomUserAgent方法设置UserAgent,再通过loadUrl加载具体页面。

// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  // 三方应用相关信息标识
  @State customUserAgent: string = ' DemoApp';

  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
      .onControllerAttached(() => {
        console.info("onControllerAttached");
        try {
          let userAgent = this.controller.getUserAgent() + this.customUserAgent;
          this.controller.setCustomUserAgent(userAgent);
        } catch (error) {
          console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
        }
      })
    }
  }
}

本文参与了 【 HarmonyOS NEXT 技术问答冲榜,等你来战!】欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进