DEV Community

Cover image for HarmonyOS Flutter Practical Guide: 04-How to Debug Webview Using DevTools
shaohushuo
shaohushuo

Posted on

HarmonyOS Flutter Practical Guide: 04-How to Debug Webview Using DevTools

In "Integrating Webview in Harmony Flutter Development", it introduces how to integrate Webview in Flutter. This article is about the debugging method of Webview.

Configure Webview

In the CustomView.ets file, configure debugging permission at the lifecycle aboutToAppear:

aboutToAppear() {
webview.WebviewController.setWebDebuggingAccess(true);
}
Enter fullscreen mode Exit fullscreen mode

Find the port of devtools

Run the App, use the hdc command to connect to the device, and find the relevant port

# Connect to the device
hdc shell

# Find the relevant process
cat /proc/net/unix | grep devtools

#0: 00000002 0 10000 1 1 2318187 @webview_devtools_remote_43406
#0: 00000002 0 10000 1 1 20785 @webview_devtools_remote_6312
Enter fullscreen mode Exit fullscreen mode

As shown above, webview_devtools_remote_43406 is the page we want to debug

Enable port forwarding

Forward the port in the device to the development computer

hdc fport tcp:9222 localabstract:webview_devtools_remote_43406

# Forwardport result:OK
Enter fullscreen mode Exit fullscreen mode

Find Webview in Chrome and start debugging

Open the chrome://inspect/#devices page in Chrome and observe that the relevant page appears at the RemoteTarget in the page

Select the page to be scheduled, click inspect, and the DevTools pops up Window, open page scheduling

Others

If you want to inject js code into Webview, you can use the runJavaScript method to inject JavaScript scripts in the Web component configuration, such as

Web({src: 'https://baidu.com', controller: this.webviewController})
.domStorageAccess(true)
.fileAccess(true)
.mixedMode(MixedMode.All)
.databaseAccess(true)
.javaScriptAccess(true) 
.onPageEnd(() => { 
this.webviewController.runJavaScript("document.querySelector('meta[http-equiv=\"Content-Security-Policy\"]').remove()"); 
})
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)