HarmonyOS鸿蒙Next中webview https页面如何限制http资源访问

HarmonyOS鸿蒙Next中webview https页面如何限制http资源访问 1、webview https页面如何限制http资源访问
2、如果限制了,是否可以针对特定域名,放开https页面访问http资源的限制

3 回复
  1. mixedMode默认就不允许加载HTTP和HTTPS混合内容,请看下是否设置了mixedMode属性。

    https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/ts-basic-components-web-V13#mixedmode

  2. 或者,采用mixedMode为all,都允许

    通过onLoadIntercept拦截接口可以根据业务做相应处理,例如选择拉起应用或打电话等。

    https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-web-V5#onloadintercept10

Web({ src: $rawfile('call.html'), controller: this.controller })

  .onLoadIntercept((event) => {

    if (event) {

      let url: string = event.data.getRequestUrl();

      if (url.indexOf('store://') === 0) {

        const want: Want = {

          uri: `store://appgallery.huawei.com/`

        }

        const context = getContext(this) as common.UIAbilityContext;

        context.startAbility(want).then(() => {

        }).catch(() => {

        })

        return true;

      }

    }

    return false;

  })

暂无,没有这种直接针对特定域名进行特殊配置的API

更多关于HarmonyOS鸿蒙Next中webview https页面如何限制http资源访问的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,可以通过配置WebView的安全策略来限制HTTPS页面访问HTTP资源。具体步骤如下:

  1. 使用WebViewsetMixedContentMode方法设置混合内容模式。setMixedContentMode方法可以设置为以下三种模式之一:

    • MIXED_CONTENT_ALWAYS_ALLOW:允许加载所有HTTP资源。
    • MIXED_CONTENT_NEVER_ALLOW:禁止加载所有HTTP资源。
    • MIXED_CONTENT_COMPATIBILITY_MODE:根据兼容性模式加载HTTP资源。
  2. 为了限制HTTPS页面访问HTTP资源,应将setMixedContentMode设置为MIXED_CONTENT_NEVER_ALLOW。这样,WebView将阻止加载任何HTTP资源,确保页面仅加载HTTPS资源。

示例代码如下:

import webview from '@ohos.web.webview';

let webView = webview.WebView.create();
webView.setMixedContentMode(webview.MixedContentMode.MIXED_CONTENT_NEVER_ALLOW);

通过上述配置,WebView在加载HTTPS页面时将自动阻止加载HTTP资源,确保页面的安全性。

在HarmonyOS鸿蒙Next中,WebView默认允许加载HTTPS和HTTP资源。为了限制WebView仅加载HTTPS资源,可以通过以下步骤实现:

  1. 设置WebViewClient:在WebView中设置自定义的WebViewClient,重写shouldInterceptRequest方法。
  2. 检查URL协议:在shouldInterceptRequest方法中检查请求的URL,如果发现是HTTP资源,则返回null或拦截请求。

示例代码如下:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        if (url.startsWith("http://")) {
            // 拦截HTTP请求
            return null;
        }
        return super.shouldInterceptRequest(view, request);
    }
});

通过这种方式,可以确保WebView仅加载HTTPS资源,增强应用的安全性。

回到顶部