HarmonyOS Web组件加载富文本时如何引用本地css和js

新闻类app,新闻详情都是接口返回的富文本样式,app端封装html 数据时,如何引入本地css和js文件。

HarmonyOS
2024-09-04 10:59:12
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

参考代码:

import webview from '@kit.ArkWeb' 
import business_error from '@kit.BasicServicesKit'; 
import { buffer } from '@kit.ArkTS'; 
@Entry 
@Component 
export struct WebDemo { 
  controller = new webview.WebviewController() 
  @State userAgent:string ="Mozilla/5.0 (Phone; OpenHarmony 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 ArkWeb/4.1.6.1 Mobile" 
  htmlContent = '<html><head></head><body>Source:<pre>source</pre></body></html>' 
  aboutToAppear(): void { 
    webview.WebviewController.setWebDebuggingAccess(true); 
    const context = getContext() 
    const style = context.resourceManager.getRawFileContentSync('style.css') 
    this.htmlContent = `<style>${buffer.from(style).toString()}</style>${this.htmlContent}` 
    console.log(`test: ${this.htmlContent}`) 
  } 
  build() { 
    Column() { 
      Button('loadData') 
        .onClick(() => { 
          try { 
            // 点击按钮时,通过loadData,加载HTML格式的文本数据 
            this.controller.loadData( 
              this.htmlContent, 
              "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: $rawfile('index.html'), controller: this.controller }) 
    } 
  } 
} 
//这段就是读取rawfile下的style.css文件,然后拼接到html上 
const context = getContext() 
const style = context.resourceManager.getRawFileContentSync('style.css') 
this.htmlContent = `<style>${buffer.from(style).toString()}</style>${this.htmlContent}` 
console.log(`test: ${this.htmlContent}`)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
分享
微博
QQ
微信
回复
2024-09-04 15:15:38
相关问题
HarmonyOS Web组件加载文本异常
1117浏览 • 1回复 待解决
HarmonyOS web控件加载文本,字太小
1297浏览 • 1回复 待解决
HarmonyOS 加载文本问题
886浏览 • 1回复 待解决
文本web组件中无法展示
2584浏览 • 1回复 待解决
HarmonyOS web组件如何加载本地字库?
1030浏览 • 1回复 待解决
HarmonyOS 如何支持表情文本
1506浏览 • 2回复 待解决
HarmonyOS 文本加载页面适配不兼容
748浏览 • 1回复 待解决
HarmonyOS 文本组件问题
1117浏览 • 1回复 待解决
HarmonyOS web组件js交互
645浏览 • 1回复 待解决
如何使用Web组件加载本地的html文件?
1579浏览 • 1回复 待解决
HarmonyOS Text组件文本解析问题
598浏览 • 1回复 待解决