9

I'm new to Flutter, and currently, I'm making a very simple app, which is just a WebView. My question is how can I insert this code into my Flutter WebView?

footer#footer, div#st_notification_1, #sidebar_box {
    display: none!important;
}

As of the moment, I'm trying to use WebView plugin by the Flutter Team on one of my application tabs. The website I'm trying to load and hiding the footer after is:

Syncshop

below is my code for that tab Webview that I'm trying to hide the footer

UPDATED: FIXED IT. The code below is working for me Note: I also re-inspect the website and changed the getElementsById to getElementsByClassName corresponding to the class name of the footer on the website above.

Note2: There are plenty of WebView apps in Flutter packages, I'm using the Flutter Webview by the Flutter team.

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

class ProfileAccount extends StatefulWidget {
  ProfileAccount({Key key}) : super(key: key);

  @override
  _ProfileAccountState createState() => _ProfileAccountState();
}

class _ProfileAccountState extends State<ProfileAccount> {
    WebViewController _myController;
    final Completer<WebViewController> _controller =
     Completer<WebViewController>();
  @override
  Widget build(BuildContext context) {
    return SafeArea(
          child: Scaffold(
            body: WebView(
              initialUrl: 'https://syncshop.online/en/login',
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (controller) {
                _myController = controller;
              },
          onPageFinished: (initialUrl) {
            _myController.evaluateJavascript("document.getElementsByClassName('footer-container')[0].style.display='none';");
          },
        )
      ),
    );
  }
}
Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
KDC
  • 591
  • 1
  • 10
  • 26

2 Answers2

8

You can try

flutterWebviewPlugin.evalJavascript('alert("Hello World")')

Remember that the evalJavascript() expects the JS not HTML, So you can't use like

flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">alert("Hello World")</script>')

Here is the complete example for your reference,

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

class JSInWebView extends StatefulWidget {
  @override
  JSInWebViewState createState() {
    return new JSInWebViewState();
  }
}

class JSInWebViewState extends State<JSInWebView> {
  final flutterWebviewPlugin = new FlutterWebviewPlugin();
  // alternatively you can define variable as var js = "YOUR_SCRIPT"; and use it inside evalJavascript

  @override
  void initState(){
    super.initState();
    flutterWebviewPlugin.evalJavascript("alert('Hi, I just executed')");
  }

  @override
  void dispose() {
    flutterWebviewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: 'https://google.com',
      hidden: true,
      appBar: AppBar(title: Text("Elite")),
    );
  }
}
Leonardo Rignanese
  • 865
  • 11
  • 22
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
  • Hi where can I include it in my code above? im kinda lost tbh – KDC Dec 10 '19 at 07:59
  • You can pass inline. I haven't tried with strings but it's worth giving a try to define javascript in the string and then pass it to `evalJavascript()` function. – Kiran Maniya Dec 10 '19 at 08:47
  • okay ill try it later. Another question, should I pass inline this code within javascript? ``` footer#footer, div#st_notification_1, #sidebar_box { display: none!important; } ``` is that what you mean ? – KDC Dec 11 '19 at 03:34
  • this is not javascript code. this is css. If you want to change the css using javascript, do as, ```const foot = document.querySelector('#footer'); foot.setAttribute('style', 'text-align: center');``` – Kiran Maniya Dec 11 '19 at 05:11
  • also, there is a good post here. https://www.digitalocean.com/community/tutorials/how-to-modify-attributes-classes-and-styles-in-the-dom to refer – Kiran Maniya Dec 11 '19 at 05:14
  • last question sorry if im asking too much i just really cant find good solutions to solve this problem, I just found out that ```flutterWebviewPlugin.evalJavascript``` will not work unless its inside an AppBar(), so I should just put css inside the dom and then pass that javascript into ```flutterWebviewPlugin.evalJavascript```? – KDC Dec 11 '19 at 06:04
  • If possible, Update the question and place the code you are trying with. So i can understand the issue. You can define javascript into a variable (as a string) and then you can pass it to `evalJavascript()` function. – Kiran Maniya Dec 11 '19 at 06:52
  • okay ill update the question I think what I got right now (using WebView plugin on one of my tabs) is closer and really describes my problem – KDC Dec 11 '19 at 07:07
  • nevermind I fixed it. I will update my question with my codes for some beginners reference in the future – KDC Dec 11 '19 at 07:27
  • Aah, I also updated the answer. Still, update the question for beginner's reference. You have a good question, Upvoting.. – Kiran Maniya Dec 11 '19 at 07:29
  • 1
    Thanks for your help! Now im just trying to find out how to cache websites with the official flutter dev webview plugin. Regards – KDC Dec 11 '19 at 07:55
  • I tried flutterWebviewPlugin.evalJavascript("document.getElementById('head').style.display = 'none';"); . But this is not working properly. its is working when i rerun app , not in first run. – Thisara Subath Mar 06 '20 at 09:37
  • `head` is not a id, so you can't use `getElementById()` with it. use `document.head.style.display = 'none'` – Kiran Maniya Mar 06 '20 at 09:40
-1

Thanks for the answers here. I combined them with this javascript answer to make a function for easily injecting a full css file. This is handy if you have a large number of overrides or you want to track them over time in a separate file.

In your webview:

onPageFinished: (finish) async {
    // Override CSS values
    String overrideJs = await jsInjectionString(context, 'assets/my_css_override.css');
    _webController.evaluateJavascript(overrideJs);    
 },

Elsewhere:

  // Build the javascript injection string to override css
  Future<String> jsInjectionString(BuildContext context, String asset) async {
    String cssOverride = await loadStringAsset(context, asset);
    return "const cssOverrideStyle = document.createElement('style');"
        "cssOverrideStyle.textContent = `$cssOverride`;"
        "document.head.append(cssOverrideStyle);";
  }

  // Load a string asset
  Future<String> loadStringAsset(BuildContext context, String asset) async {
    return await DefaultAssetBundle.of(context).loadString(asset);
  }
Emilie
  • 265
  • 1
  • 9