HarmonyOS Web通过loadData加载html不显示内容?

场景:文章详情展示,html模板是在rawfile中,里面的具体内容是从文章接口中获取

结果:html中带了color:\#FC6626这种颜色样式,就显示不出来里面的文字

阅读 576
1 个回答

文档说明:若html中的富文本中带有注入\#等特殊字符,建议使用带有两个空格的loadData函数,将baseUrl和historyUrl置为空。

因为\#是特殊字符,需要转义特殊处理,请按照以下代码进行加载

示例参考如下:

import web_webview from '@ohos.web.webview';
import business_error from '@ohos.base';
@Entry
@Component
struct WebPage {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  htmlStr = `<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<meta name="aplus-terminal" content="1">
<meta name="format-detection" content="telephone=no,email=no,adress=no">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
<meta name="aplus-touch" content="1">
</head>
<body>
<div class="container">
<span style="color:#FC6626;font-size:16px;">火得让人猝不及防。哪哪都是ChatGPT。</span>
</div>
</body>
</html>`

  //

  build() {
    Column() {
      Button('loadData')
        .onClick(() => {
          try {
            this.controller.loadData(this.htmlStr,"text/html", "UTF-8", " ", " ")
          } catch (error) {
            let e: business_error.BusinessError = error as business_error.BusinessError;
            console.error(`ErrorCode: ${e.code}, Message: ${e.message}`);
          }
        })
      Web({ src: '', controller: this.controller })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进