目录

Web组件如何实现拦截网络超链接后在浏览器中打开

问题现象

Web中加载包含网络图片链接的HTML网页,如何实现点击网络图片链接后跳转至手机浏览器打开?

效果预览

背景知识

解决方案

import { webview } from '@kit.ArkWeb';
import { common, Want } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebJumpBrowser {
  controller: webview.WebviewController = new webview.WebviewController();
  context = this.getUIContext().getHostContext() as common.UIAbilityContext;

  build() {
    Column() {
      Web({
        // 此处地址实际使用过程中替换为真实地址
        src: 'www.example.com',
        controller: this.controller
      })
        .fileAccess(false)
        .geolocationAccess(false)
        .domStorageAccess(true)
        .onLoadIntercept((event) => {
          // 拦截所有请求
          let url = event.data.getRequestUrl();
          console.info('Intercepting URL: ' + url);
          // 判断是否需要外部打开(这里示例所有https链接都外部打开)
          if (url.startsWith('https://')) {
            // 调用方法在外部浏览器打开
            this.openInExternalBrowser(url);
            return true;
          }
          return false;
        });
    }
    .width('100%')
    .height('100%');
  }

  // 在外部浏览器打开链接的方法
  openInExternalBrowser(url: string) {
    try {
      let want: Want = {
        action: 'ohos.want.action.viewData',
        entities: ['entity.system.browsable'],
        uri: url,
      };
      this.context.startAbility(want)
        .then(() => {
          console.info('Open browser successfully');
        })
        .catch((err: BusinessError) => {
          let code = (err as BusinessError).code;
          let message = (err as BusinessError).message;
          console.error(`startAbility failed, code is ${code}, message is ${message}`);
        });
    } catch (error) {
      console.error(`An unexpected error occurred. Error code: ${error.code}, message is ${error.message}`);
    }
  }
}