스터디/Flutter+Dart

[Flutter] Webview에서 JS로 Flutter앱의 기능 실행하기

Dalmangyi 2022. 7. 15.

InAppWebview 패키지를 사용하다보면, 웹에서 앱으로 신호를 줘야할때가 생기는데

그럴때 사용하는 함수가 [window.flutter_inappwebview.callHandler] 입니다.

 

사용방법은 아래와 같습니다.

 

1. 자바스크립트 핸들러 추가

Flutter에서 onWebViewCreated 함수가 실행될때, "myHandlerName" 핸들러 이름을 가진 자바스크립트 핸들러를 추가합니다.

onWebViewCreated: (controller) {
  controller.addJavaScriptHandler(handlerName: 'myHandlerName', callback: (args) {
    print(args);
    
    return {
      'bar': 'bar_value', 'baz': 'baz_value'
    };
  });
},

 

 

2. 웹쪽 코드

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    </head>
    <body>
        <h1>JavaScript Handlers</h1>
        <script>
            window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
                window.flutter_inappwebview.callHandler('myHandler')
                  .then(function(result) {
                    console.log(JSON.stringify(result));
                });
            });
        </script>
    </body>
</html>

 

 

 

 

+. 예외상황

하지만 이렇게 간단한 코드임에도 안 될때가 있습니다.

"window.flutter_inappwebview.callHandler is not a function"

js에서 잘 되던 window.flutter_inappwebview.callHandler 함수를 갑자기 찾을 수 없다고 하는데...

간단히 해결이 가능합니다.

 

callHandler 대신, _callHandler를 사용하면 됩니다..

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    </head>
    <body>
        <h1>JavaScript Handlers</h1>
        <script>
            window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
            	if (window.flutter_inappwebview.callHandler){ 
                    window.flutter_inappwebview.callHandler('myHandler')
                      .then(function(result) {
                        console.log(JSON.stringify(result));
                    });
                }else{
                	window.flutter_inappwebview._callHandler('myHandler')
                      .then(function(result) {
                        console.log(JSON.stringify(result));
                    });
                }
            });
        </script>
    </body>
</html>

 

https://github.com/pichillilorenzo/flutter_inappwebview/issues/218

 

 

 

 

+. 기타 inappwebview 설명

https://inappwebview.dev/docs/javascript/communication/

댓글