Catch window.open() or target _blank Webview_flutter

334 views Asked by At

I'm currently using webview_flutter for webview appearance. But the problem is I can't find the way to get button tap on webview which is window.open(url) or target="_blank".

I want to prevent when it matches above condition.onNavigationRequest is provided to prevent but the solution how to get window.open(url) or target="_blank" is unknown because url is only url string.

final navigationDelegate = NavigationDelegate(
  onNavigationRequest: (request) {
     final url = request.url; // only url string not window.open() so I can't prevent
   },
);

Due to some security I can't use inappwebview

Thank you a lot for your help.

1

There are 1 answers

0
Thang Phi On BEST ANSWER

Finally I can catch window.open() by using addJavaScriptChannel. Make a channel in WebView_flutter to listen whether you tap on window.open().

await webViewController.addJavaScriptChannel(
   'callingMethod',
    onMessageReceived: (message) {
        _onMessageReceived(message);
    },
);

final navigationDelegate = NavigationDelegate(
   onPageFinished: (url) => _onPageFinished(url),
);

await webViewController.setNavigationDelegate(navigationDelegate);
Future<void> _onPageFinished(String url) async {
    // Open here is window.open() on JS
    // Make javascript including catch window.open() and channel
    await webViewController.runJavaScript('''
       open = (str) => { nativeMethod.postMessage("open=" + str); };
       var Android = {
           callingMethod: (str) => {
            callingMethod.postMessage(str);
       }
    };
    ''');

Future<void> _onMessageReceived(JavaScriptMessage message) async {
    String key = message.message.substring(0, message.message.indexOf("="));
    String value = message.message.substring(message.message.indexOf("=") + 1);

    if (key == "open") {
      // do something
    }
  }