admin管理员组

文章数量:1426087

I've build a PhoneGap app which which makes use of an iframe which is bundled with the app and I'm am trying to pass e message from the iframe to the parent which doesn't seem to be working when I run the app on an actual iPad; however it works fine when I run the app in the browser on the same device.

Here is the code I'm using inside the iframe to send a message, note that I'm using HammerJS to capture some events:

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
});

and the code I'm using to get the message:

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

I've build a PhoneGap app which which makes use of an iframe which is bundled with the app and I'm am trying to pass e message from the iframe to the parent which doesn't seem to be working when I run the app on an actual iPad; however it works fine when I run the app in the browser on the same device.

Here is the code I'm using inside the iframe to send a message, note that I'm using HammerJS to capture some events:

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
});

and the code I'm using to get the message:

window.addEventListener('message',function(event) {
    alert(event.data);
},false);
Share Improve this question edited Aug 29, 2014 at 10:54 Petar Vasilev asked Aug 28, 2014 at 16:55 Petar VasilevPetar Vasilev 4,7556 gold badges47 silver badges78 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

And the answer is to use "file://" as the domain name so the code will look like this:

var domain = 'file://';

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

Try with using

var domain = '*';

Normally this should be because of cross domain problem, see more here

You will need to use:

parent.postMessage(message,"*");

Since phonegap/cordova pages are served at "file://" and according to https://developer.mozilla/en-US/docs/Web/API/Window/postMessage

"...posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future."

本文标签: javascriptpostMessage in PhoneGap not workingiframe to parent messagingStack Overflow