Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cordova cross-domain file:// iframe contentwindow communication

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.

like image 717
mircoc Avatar asked Nov 02 '15 09:11

mircoc


People also ask

How to access cross domain iframe?

To access cross-domain iframe, the best approach is to use Javascript's postMessage() method. This method provides a way to securely pass messages across domains.

Can two iframes communicate?

Communicating directly between iframes is also possible by combining window. parent with target as defined above. In conclusion, the postMessage method is a more dynamic alternative to the single DOM, better suited if you load multiple pages in one iframe, but not always easier and it still requires the use of the DOM.


1 Answers

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.

like image 129
jjdltc Avatar answered Sep 20 '22 14:09

jjdltc