【问题标题】:postMessage in PhoneGap not working - iframe to parent messagingPhoneGap 中的 postMessage 不起作用 - iframe 到父消息传递
【发布时间】:2014-08-28 16:55:04
【问题描述】:

我已经构建了一个 PhoneGap 应用程序,它使用与应用程序捆绑在一起的 iframe,我正在尝试将 e 消息从 iframe 传递给父级,当我运行时它似乎不起作用实际 iPad 上的应用程序;但是,当我在同一设备上的浏览器中运行该应用程序时,它工作正常。

这是我在 iframe 中用于发送消息的代码,请注意我使用 HammerJS 来捕获一些事件:

var domain = 'http://' + document.domain;

$('body').hammer().on("swipe", "", function(event) {
    var message = event.gesture.direction;
    parent.postMessage(message,domain); //send the message and target URI
});

以及我用来获取消息的代码:

window.addEventListener('message',function(event) {
    alert(event.data);
},false);

【问题讨论】:

    标签: javascript ios cordova iframe


    【解决方案1】:

    答案是使用“file://”作为域名,所以代码如下所示:

    var domain = 'file://';
    
    $('body').hammer().on("swipe", "", function(event) {
        var message = event.gesture.direction;
        parent.postMessage(message,domain); //send the message and target URI
    });
    

    【讨论】:

    • 不适合我,这就是我从页面调用的方式 dziban.co.in/test/…);" class="ui-btn ui-corner-all">打开窗口,收到与您相同的信息,并在 postMessage 中尝试了 file:// 和 dziban.co.in/test/postmsg.php,但没有运气。你能解释一下你是如何从html打开iframe的吗?
    • 这不是从 html 打开 iframe,而是将数据从 iframe 传递到父网站,您可以在此处阅读更多信息:developer.mozilla.org/en-US/docs/Web/API/Window/postMessage。至于您要做什么,您无法从 JavaScript 打开 iframe,但您可以打开一个新窗口,您可以在此处阅读更多信息:w3schools.com/jsref/met_win_open.asp
    • @JayaVishwakarma 请问您是如何解决这个问题的?我们正在使用parent.postMessage(message, '*');,它可以在 Android 上运行,但我们无法让它在 iOS 上运行
    • @jablesauce 您是否将 iframe 域列入白名单?请参阅github.com/phonegap/phonegap/wiki/iFrame-Usage -> IOS:“要将域列入白名单,请将其添加到 Cordova.plist 文件中的 ExternalHosts 数组中。”
    • @jablesauce 你找到解决办法了吗?
    【解决方案2】:

    尝试使用

    var domain = '*';
    

    一般应该是跨域问题,see more here

    【讨论】:

      【解决方案3】:

      你需要使用:

      parent.postMessage(message,"*");
      

      因为 phonegap/cordova 页面在“file://”和https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage提供服务

      "...在文件的页面上发布消息:URL 当前要求 targetOrigin 参数为“*”。file:// 不能用作安全限制;将来可能会修改此限制。 "

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-20
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        相关资源
        最近更新 更多