【问题标题】:how can I send custom message from my in app-browser to my ionic app如何将自定义消息从我的应用程序浏览器发送到我的离子应用程序
【发布时间】:2020-05-11 11:18:29
【问题描述】:

我正在尝试将自定义有效负载从我的 inAppBrowser 中的 js 发送到我的 ionic 应用程序。我已经知道如何使用以下方法将数据发送到 inAppbrowser:

iab.executeScript({code:`alert(2)`});

但是在我看到的 github 网站上没有正确记录发回数据:

inAppBrowserRef.addEventListener('message', messageCallBack);

上面只展示了如何让你的 ionic 接收它,但没有展示 javascript 是如何发送它的。我需要有关如何使 inAppbrowser 发送此自定义消息的帮助。

【问题讨论】:

  • 你找到解决办法了吗?
  • @Rajasekar 是的,我做到了。你也有问题吗?
  • 是的,我在将消息从我的应用程序发送到应用程序内浏览器时遇到了困难。我需要多次发送(在多个事件期间)。你能帮忙吗
  • @Rajasekar 在下面查看我的答案,如果这对您没有帮助,请针对您的确切问题创建一个问题,我将发布具体答案。

标签: ionic-framework ionic4 inappbrowser


【解决方案1】:
import { Component } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  ref: InAppBrowser;
  constructor(private iab: InAppBrowser) {

  }

  openBlank() {

    var payload = JSON.stringify({
      "currency": "",
      "exp": "",
      "success_title": "",
      "success_message": ""
    })

    var init = false;
    
    var ref = this.iab.create('https://random.com/', '_blank', 'location=yes');
    ref.on('loadstop').subscribe(event => {
      if(!init){
        console.log(' jeffery received')
        //ref.executeScript({ code: "webkit.messageHandlers.cordova_iab.postMessage('"+payload+"')" });
        ref.executeScript({ code: "jsFunction('" + payload + "');" });
        init = true;
      }
    });

    ref.on('message').subscribe((event) => {

      const postObject:any = event
       console.log(postObject.data.type)
       console.log(JSON.stringify(postObject.data))
    })

    ref.on('loadstart').subscribe(event => {
      if(init){
        var shouldClose = this.getUrlParameter(event.url.replace(/%22/g, "\""), "shouldClose");
        if(shouldClose){
          var data = this.getUrlParameter(event.url.replace(/%22/g, "\""), "data");
          var jsonObj = JSON.parse(data);
          ref.close();
        }
      }
    });
  }

   getUrlParameter = (url, name) => {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(url);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  }

  openSystem() {
    this.iab.create(`https://jamibot.com`, `_system`);
  }


}

【讨论】:

  • @Rajasekar 这应该会有所帮助
  • 感谢您的回复@oto-obong Eshiett。我想明白一件事。这里的“jsFunction”应该是外部应用程序内部的全局函数。是这样吗?。
  • @Rajasekar 是的,这是在 HTML 页面中被 inAppbrowser 调用的函数,在我们的例子中是 random.com
  • 感谢您对@Oto-Obong Eshiett 的支持
  • 您是否使用 javascript 的 postMessage 将消息从浏览器发送到应用程序。它也适用于系统浏览器吗?
猜你喜欢
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 2020-06-25
  • 2016-11-06
  • 1970-01-01
相关资源
最近更新 更多