首页 > 解决方案 > 无法从 inappbrowser 向 Cordova 应用程序发布消息

问题描述

我正在使用此模块 ( https://github.com/apache/cordova-plugin-inappbrowser ) 在我的 Cordova 应用程序中打开外部链接。但是,postMessage文档中的示例不起作用。

我需要能够让inappbrowser实例与父级(的opener)进行通信。鉴于没有opener对象inappbrowser,我查看了 repo 的文档和测试,我无法重现postMessageAPI 以在inappbrowser实例和主 Cordova 应用程序(父级)之间进行通信。

这是一个取自此 repo 中的文档/测试的简单示例:

const ref = cordova.InAppBrowser.open('http://www.google.com', '_blank');

ref.addEventListener('loadstop', () => {
  console.log('loadstop has been fired'); // this fires

  // when this has been executed, `webkit` variable doesn't exist inside of the `inappbrowser`
  // instance
  ref.executeScript({
    code: `(() => {
      var message = "TESTING!!!";
      webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));
    })()`
  });
});

// this is never fired
ref.addEventListener('message', (...args) => {
  console.log('MESSAGE RECEIVED FROM IN_APP_BROWSER', ...args);
});

标签: ioscordovaionic-frameworkphonegap-pluginshybrid-mobile-app

解决方案


该文档指向尚未发布的版本。我指出了3.1.0-dev这个包的版本,实现就像一个魅力。


推荐阅读