1 | initial version |
You can use the following code to remove the header of a website on Flutter WebView:
class MyWebView extends StatelessWidget {
final String url;
MyWebView({required this.url});
@override
Widget build(BuildContext context) {
return Scaffold(
body: WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (String url) {
removeHeader(context);
},
),
);
}
void removeHeader(BuildContext context) async {
String removeHeaderJS = '''
javascript:(function() {
var header = document.getElementsByTagName('header')[0];
header.style.display = 'none';
})();
''';
await Future.delayed(Duration(milliseconds: 500));
await (await WebView.platformViewsRegistry.getPlatformViewsController((context.findRenderObject() as RenderBox).parentData!.size!.toRect())).evaluateJavascript(removeHeaderJS);
}
}
In this code, we are using the Javascript getElementsByTagName
method to get the first header
element on the page and then setting its display
property to none
to hide it. We are calling the removeHeader
method when the page has finished loading using the onPageFinished
callback of the WebView. Finally, we are using the evaluateJavascript
method to execute the removeHeaderJS code on the WebView.