Have a Question?

If you have any question you can ask below or enter what you are looking for!

Question Detial

I found that i can do cross-domain communication from a page on file:// and an iframe hosted on a remote host with the contentWindow property of the iframe.

For example on the device I have an html page at the url file://.../index.html that loads cordova and contains an iframe:

<script type="text/javascript" src="cordova.js"></script>
<iframe id="appframe"></iframe>

On this page I can execute a javascript that loads the iframe and save a reference of an object in the iframed page like this:

var iframe = document.getElementById("appframe");
iframe.onload = function(){
    iframe.contentWindow.cordova = window.cordova;
}
iframe.src = "http://www.example.com/appframe.html";

Now on the page inside the iframe, http://www.example.com/appframe.html, i can execute a cordova call, for example:

cordova.exec(null, null, "StatusBar", "hide", []);

and this unexpectedly works, calling the native layer of the StatusBar cordova plugin and hiding the statusbar.

My question is:

Is this safe to use or is an hack that won't work in future version of the browsers?

I tested it on iOS 9 and Android 5 devices.

Answers

Cy Rossignol

5:12pm 6th September 2016

I think that probably you have in your config.xml the following tag.

<access origin="*" />

as described here https://cordova.apache.org/docs/en/latest/guide/appdev/whitelist/ you could restrict the cross domain policy to specified domains used as value of the property "origin" instead of using a wildcard.

So if you are using the wildcard value, this should be the desired behaviour.

Mike Patrick

7:40pm 12th October 2016

I Believe that the safer way to communicate between frames is postMessage as described in MDN, do it in a different way could cause inconsistency between devices (Remember how fragmented is android and how painful could be the backward compatibility with 4.3 and below)

So, you could get the iFrame element and then post a msg like

otherWindow.postMessage(InfoToSend, "*");

In the same way you could listen to that event inside the frame:

window.addEventListener("message", receiveMessage, false);

This will no cause cross-frame issues and it will be the safer way to pass information, the bad news is that you will not be able to pass the window.cordova instance, so you will need to establish a conversation between the iFrame and the window.top frame.