簡體   English   中英

Flutter web app in the Android webview calling method of injected Android object

[英]Flutter web app in the Android webview calling method of injected Android object

I have this situation: there is the android/Kotlin app, which has the webview, which loads the Flutter web app from the Internet URL.

需要明確的是 - 在 Flutter 中沒有 webview 的情況。 完全相反 - Flutter 用於構建 web 應用程序,該應用程序在 Android Z5A98E28440FD01418DED478DZ 中呈現。

我們按照谷歌的說明創建了 webview 接口: https://developer.android.com/guide/webapps/webview

即 Kotlin 在 Z5A98E2840FD0141780D754E48C608D4 內創建 Android object。

我可以從 Chrome 調試工具控制台訪問這個 Javascript Android object,同時調試 Z5A98E2840FD01401784D854E。

即 Android / Kotlin 部分沒問題。

但是,當從 Flutter Z2567A5EC9705EB7AC2C984033E0618 調用時,找不到 Android object。 我交叉檢查了 Flutter web 應用程序可以調用警報 function。

有人可以告訴我如何調用注入的 Android object 嗎?

Flutter web 應用程序的代碼:

void webViewExit() {
  print("User command: Exit webview.");

  try {
    js.context.callMethod("Android.onExitPressed");
  } catch (e) {
    print(e);
  }
}

chrome devtools 控制台中的結果:

User command: Exit webview.
NoSuchMethodError: method not found: 'apply' on null

這直接在連接到 webview 的 devtools 控制台中工作:

Android.onExitPressed();

這也有效(來自 Flutter webview webapp):

void webViewExit() {
  print("User command: Exit webview.");

  try {
    // js.context.callMethod("Android.onBackPressed");
    js.context.callMethod("alert", ["Calling Alert works!"]);
  } catch (e) {
    print(e);
  }
}

我找到了解決方法:

I added the predefined function into the static index.html page of the Flutter web app:

索引.html

  ...
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('flutter-first-frame', function () {
        navigator.serviceWorker.register('flutter_service_worker.js');
      });
    }

    // Added JS function starts here

    function onExitPressed() {
      console.log("Called onExitPressed in webview JS.");
      Android.onExitPressed();
    }
    // Added JS function ends here

  </script>
  <script src="main.dart.js" type="application/javascript"></script>
  ...

現在來自 Flutter web 應用程序的調用有效:

void webViewExit() {
  print("User command: Exit webview.");

  try {
    js.context.callMethod("Android.onExitPressed", []);
  } catch (e) {
    print(e);
  }
}

我認為原因是 Android object 在加載並啟動 dart 的 main.dart.js 之后注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM