FlutterWebとNativeAppで交信してみた

    function js2Dart(message) {
      console.log(message);
      window.postMessage(message, "*");
    }

    function js2Swift(message) {
      console.log(message);
      webkit.messageHandlers.js2Swift.postMessage(message);
    }

    function js2Java(message) {
      console.log(message);
      Android.js2Java(message);
    }

    function js2Native(message) {
      console.log(message);
      const ua = navigator.userAgent
      if (/android/i.test(ua)) {
        js2Java(message)
      }
      else if (/iPad|iPhone|iPod/.test(ua)) {
        js2Swift(message)
      }
    }
window.addEventListener("message", (event) {
    _incrementCounter();
});
 void _dart2Js() {
    _incrementCounter();
    setState(() {
      context.callMethod('js2Native', ['dart2Js']);
    });
 }

 floatingActionButton: FloatingActionButton(
     onPressed: _dart2Js,
     tooltip: 'Increment',
     child: const Icon(Icons.add),
 ),
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        webView = binding.webView;
        webView.addJavascriptInterface(new WebAppInterface(getContext()), "Android");
        webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://demo.mymyser.com/index.html");
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView.loadUrl("javascript:postMessage('Send Native Message.');");
            }
        });
    }
    @JavascriptInterface
    public void js2Java(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
        let config = WKWebViewConfiguration()
        let userContentController: WKUserContentController = WKUserContentController()
        userContentController.add(self, name: "js2Swift")
        config.userContentController = userContentController

        webView = WKWebView(
            frame: CGRect(x: 0, y: 64,
                          width: view.frame.size.width,
                          height: view.frame.size.height-64),
            configuration: config
        )
    @IBAction func onClickButton (_ sender: UIButton) {
        webView?.evaluateJavaScript("js2Dart('Send Native Message');", completionHandler: { (object, error) -> Void in
            print("⭐️:Send Native Message")
        })
    }
extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "js2Swift") {
             print("⭐️: \(message.body)")
        }
    }
}

コメントする