HarmonyOS 如何在web组件中给html注入样式

HarmonyOS
2024-12-17 14:34:52
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

参考demo给style标签注入样式:

//ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();
  private customStyle: string =
    'html, body {margin: 0; padding: 0; overflow: hidden; touch-action: none; background:#ace}';

  aboutToAppear() {
    // 配置Web开启调试模式
    web_webview.WebviewController.setWebDebuggingAccess(true);
  }

  build() {
    Column() {

      Button('style').onClick((event: ClickEvent) => {

        this.webviewController.runJavaScript(`const head = document.head;
                                              console.log(head);
                                              const style = document.createElement('style');
                                              style.appendChild(document.createTextNode("${this.customStyle}"))
                                              head.appendChild(style)
        `)
      })
      Web({ src: $rawfile('index.html'), controller: this.webviewController }).domStorageAccess(true)
    }
  }
}
// html
<!DOCTYPE html>
<html>
<head>

</head>

<body>
<h1 id="text">
    这是一个测试信息,默认字体为黑色,调用runJavaScript方法后字体为绿色,调用runJavaScriptCodePassed方法后字体为红色
</h1>
</body>
</html>
  • 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.
  • 43.
  • 44.
分享
微博
QQ
微信
回复
2024-12-17 16:24:23
相关问题
HarmonyOS web组件如何注入js文件
803浏览 • 1回复 待解决
HarmonyOS web组件注入JS代码
655浏览 • 1回复 待解决
HarmonyOS Web组件注入js怎么传递对象
1097浏览 • 1回复 待解决
HarmonyOS Web组件如何加载html字符串
1761浏览 • 1回复 待解决
HarmonyOS Web组件加载html文件异常
1473浏览 • 1回复 待解决
如何使用Web组件加载本地的html文件?
1835浏览 • 1回复 待解决
web组件html文件的加载
1663浏览 • 1回复 待解决
HarmonyOS web组件怎么获取html页面标题
514浏览 • 1回复 待解决
HarmonyOS web iframe 注入.js 问题
1267浏览 • 1回复 待解决
如何在web组件获取和设置UserAgent
1882浏览 • 1回复 待解决
HarmonyOS web组件怎么加载html字符串
692浏览 • 1回复 待解决
HarmonyOS 如何在比较早的时机注入js
485浏览 • 1回复 待解决
HarmonyOS web如何获取html内容高度
735浏览 • 1回复 待解决