ss_t_t_nの日記

開発の備忘録など

flutterでWeb画面のタイトルタグの中身をjavascript経由で取得する

class WebViewScreen extends StatefulWidget {

  final String url;

  const WebViewScreen({Key key, this.url}) : super(key: key);

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

class _WebViewScreenState extends State<WebViewScreen> {

  FlutterWebviewPlugin _plugin = FlutterWebviewPlugin();

  StreamSubscription _onStateChanged;

  String _title = "";

  @override
  void initState() {
    super.initState();
    _plugin.close();
    _onStateChanged = _plugin.onStateChanged.listen((WebViewStateChanged state) async {
      if (state.type == WebViewState.finishLoad) {
        if (!mounted) {
          return;
        }
        // ココで取得している
        _title = await _plugin.evalJavascript("document.title");
        setState(() {
          print(_title);
        });
      }
    });
  }

  @override
  void dispose() {
    _onStateChanged.cancel();
    _plugin.close();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: widget.url,
      withJavascript: true,
      appBar: AppBar(title: Text(_title)),
    );
  }
}