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

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

阅读 482
1 个回答

参考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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进