简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM