簡體   English   中英

未定義 webkit:InAppBrowser Cordova

[英]webkit is not defined : InAppBrowser Cordova

我在 Cordova 應用程序中運行來自 typescript 文件的 InAppBrowser 實例。 我的 package.json 中連接了最新的 InAppBrowser 插件。 當我在此 InAppBrowser 的 loadStop 事件上添加偵聽器時。 它不執行腳本說'webkit 未定義'。 我找不到與之相關的答案。 有沒有人知道如何解決這個問題?

代碼片段

      switchHybridApp.on("loadstop").subscribe((event: InAppBrowserEvent) => {
      console.log("Here I am 3");
      console.log('loadstop has been fired'); // this fires
      debugger;
        // when this has been executed, `webkit` variable doesn't exist inside of the `inappbrowser`
        // instance
        switchHybridApp.executeScript({ code: "\
        var message = 'this is the message';\
        var messageObj = {my_message: message};\
        var stringifiedMessageObj = JSON.stringify(messageObj);\
        webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);"
      });
      }
  );

錯誤錯誤

我嘗試過但沒有成功的解決方案

(任何窗口).webkit ....

(窗口).webkit....

好的,一年后我在這里回答這個問題以及我是如何解決它的。 所以我有無限的運行間隔來使用executeScript檢查本地和inappbrowser的localStorage,但這是一個非常糟糕的選擇。 現在 InAppBrowser 已經實現了“postMessage”。 它現在非常簡單的通信。

我所做的是,我在 inAppBrowser 中打開的網絡應用程序,我在我的 ts 文件中運行了它。

(window as any).webkit.messageHandlers.cordova_iab.postMessage(sendToNative);

請注意,objToSend 必須是一個 JSON 對象。 傳遞一個簡單的字符串是行不通的。

你可以創建這樣的對象 -

const sendToNative= 'frontCameraOpen';
const sendToNative= {message: sendToNative};
const stringifiedMessageObj = JSON.stringify(sendToNative);

現在從本機方面,使用這個事件監聽器

inAppBrowser.on('message').subscribe((dataFromIAB) => {
      alert(dataFromIAB.data.sendToNative);
});

感謝@DaveAlden 提供此功能,一年前我做錯了,哈哈。

嘗試在頁面加載事件中調用postMessage時偶然發現了同樣的問題。 在 iOS 上,這是因為webkit已在此時定義。 在 Android 上, webkit在初始頁面加載定義(注入),因此webkit.messageHandlers.cordova_iab.postMessage失敗。

可以使用 cordova_iab 代替 webkit:

const postMessage = (obj) => {
  const target = cordova_iab ?? webkit.messageHandlers.cordova_iab;
  target.postMessage(JSON.stringify(obj));
};

暫無
暫無

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

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