参考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>
参考demo给style标签注入样式: