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>
分享
微博
QQ
微信
回复
2024-12-17 16:24:23
相关问题
HarmonyOS web组件如何注入js文件
390浏览 • 1回复 待解决
HarmonyOS web组件注入JS代码
221浏览 • 1回复 待解决
HarmonyOS Web组件注入js怎么传递对象
731浏览 • 1回复 待解决
HarmonyOS Web组件如何加载html字符串
1219浏览 • 1回复 待解决
HarmonyOS Web组件加载html文件异常
1021浏览 • 1回复 待解决
如何使用Web组件加载本地的html文件?
1228浏览 • 1回复 待解决
HarmonyOS web组件怎么获取html页面标题
146浏览 • 1回复 待解决
HarmonyOS web iframe 注入.js 问题
850浏览 • 1回复 待解决
web组件html文件的加载
1171浏览 • 1回复 待解决
HarmonyOS web组件怎么加载html字符串
319浏览 • 1回复 待解决
HarmonyOS 如何在比较早的时机注入js
160浏览 • 1回复 待解决
如何在web组件获取和设置UserAgent
1414浏览 • 1回复 待解决
HarmonyOS web如何获取html内容高度
207浏览 • 1回复 待解决