0

I am using webview package and want to remove the header and footer of the website https://getmobie.de/impressum/ (I have the rights to display the page) in flutter.

Below is my code :

    class ImprintScreen extends StatefulWidget {
  const ImprintScreen({Key? key}) : super(key: key);

  @override
  State<ImprintScreen> createState() => _ImprintScreenState();
}

class _ImprintScreenState extends State<ImprintScreen> {
  late WebViewController controller;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: WebView(
        javascriptMode: JavascriptMode.unrestricted,
        initialUrl: 'https://getmobie.de/impressum',
        onWebViewCreated: (controller) {
          setState(() {
            this.controller = controller;
          });
        },
        onPageStarted: (url) {
          if (kDebugMode) {
            print('Website: $url');
          }
        },
        onPageFinished: (url) async {
          await controller.runJavascriptReturningResult(
              "document.getElementsByTagName('header')[0].style.display = 'none'"
          );
          await controller.runJavascript("javascript:(function() {" +
        "var head = document.getElementsByTagName('header')[0];" +
        "head.parentNode.removeChild(head);" +
        "var footer = document.getElementsByTagName('footer')[0];" +
        "footer.parentNode.removeChild(footer);" +
        "})").then((value) => debugPrint('Page finished Loading Javascript')).onError((error, stackTrace) => debugPrint("$error"));
        },
      )
    );
  }
}

But i am not able to remove the header and footer of the web page when displays on mobile app.

Can you please suggest what is the mistake in above code. Thanks a lot.

2 Answers 2

0

You have to call the Javascript inside the "onPageStarted" for hide header & footer .

Checkout the below code

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';


void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ImprintScreen(),
    );
  }
}

class ImprintScreen extends StatefulWidget {
  const ImprintScreen({Key? key}) : super(key: key);

  @override
  State<ImprintScreen> createState() => _ImprintScreenState();
}

class _ImprintScreenState extends State<ImprintScreen> {
  late WebViewController controller;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
          child: WebView(
            initialUrl: "https://getmobie.de/impressum/",
            javascriptMode: JavascriptMode.unrestricted,
            onWebViewCreated: (webViewController) {
              controller = webViewController;
            },
            onPageStarted: (url) {
                print('Website: $url');
                //Hide header & footer
              if (url.contains('https://getmobie.de/')) {
               //Added delayed future method for wait for the website to load fully before calling javascript
                Future.delayed(Duration(milliseconds: 900), () {
                  controller.runJavascriptReturningResult(
                        "document.getElementsByClassName('elementor elementor-7715 elementor-location-header')[0].style.display='none';"
                        "document.getElementsByClassName('elementor elementor-2727 elementor-location-footer')[0].style.display='none';"
                  );
                });
              }
            },
          ),
        )
    );
  }
}

Screenshot of hidden header

Screenshot of hidden Footer

Sign up to request clarification or add additional context in comments.

1 Comment

This question question was already asked and answered. Follow this link shorturl.at/evY26 and see if the solution provided matches the response provided or better the solution.
0

You can use the flutter_inappwebview plugin (I'm the author) and inject an UserScript at UserScriptInjectionTime.AT_DOCUMENT_START to hide or remove HTML elements when the web page loads (check JavaScript - User Scripts official docs for User Scripts details).

Here is a code example using the current latest version 6 (6.0.0-beta.18) with your URL https://getmobie.de/impressum that removes the header and footer HTML elements:

import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (!kIsWeb &&
      kDebugMode &&
      defaultTargetPlatform == TargetPlatform.android) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
  }
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("InAppWebView test"),
        ),
        body: Column(children: <Widget>[
          Expanded(
            child: InAppWebView(
              key: webViewKey,
              initialUrlRequest:
                  URLRequest(url: WebUri("https://getmobie.de/impressum")),
              initialUserScripts: UnmodifiableListView([
                UserScript(source: """
                window.addEventListener('DOMContentLoaded', function(event) {
                  var header = document.querySelector('.elementor-location-header'); // use here the correct CSS selector for your use case
                  if (header != null) {
                    header.remove(); // remove the HTML element. Instead, to simply hide the HTML element, use header.style.display = 'none';
                  }
                  var footer = document.querySelector('.elementor-location-footer'); // use here the correct CSS selector for your use case
                  if (footer != null) {
                    footer.remove(); // remove the HTML element. Instead, to simply hide the HTML element, use footer.style.display = 'none';
                  }
                });
                """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START)
              ]),
              onWebViewCreated: (controller) {
                webViewController = controller;
              },
            ),
          ),
        ]));
  }
}

Android example iOS example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.