[SalesForce] Blocked a frame with origin “https://XXX-dev-ed.lightning.force.com” from accessing a cross-origin frame

I am trying to send data from Lightning component to visualforce page on clicking of button Inside lightining component.On Clicking of button am getting error like "Blocked a frame with origin from accessing a cross-origin frame"

Component code

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global">
 <aura:attribute name="message" type="String"/>
 <ui:inputText label="Send Msg" value="{!v.message}" />
 <lightning:button label="Send to VF" onclick="{!c.sendToVF}"/>
 <aura:attribute name="vfHost" type="String" default="XXX-dev-ed.ap5.visual.force.com"/>
 <iframe aura:id="vfFrame" src="{!'https://' + v.vfHost + '/apex/MyVf'}" width="100%" height="500px;" frameBorder="0"/> 
</aura:component>

Component JSController

sendToVF : function(component, event, helper) {
    var message = component.get("v.message");
    var vfOrigin = "https://" + component.get("v.vfHost");
    var vfWindow = component.find("vfFrame").getElement().contentWindow;
    vfWindow.postMessage(message, vfOrigin);  
}

VF page

<apex:page  >
<input id="message" type="text"/>
<script>
 var lexOrigin = "https://XXX-dev-ed.ap5.lightning.force.com";
 window.addEventListener("message", function(event) {
  if (event.origin !== lexOrigin) {
            // Not the expected origin: reject message!
            return;
        }
  console.log("----Lightining message :" +event.data);
 }, false);
</script></apex:page>

Please let me know how to resolve this issue.

Best Answer

For my taste you got a lot of missleading answers here...

This behavior has nothing to do with LockerService.

Without LockerService it is exactly the same as you have already observed.

The sole reason is the fact that visualforce pages are served from a different domain than Lightning Experience (holding your Lightning Component).

This is done by Salesforce on purpose and it's considered as a security feature. You can't turn it off.

Good news: there is an officially documented practice to overcome this frontier by using window.postMessage(). With that you can implement bidirectional communication between Visualforce and Lightning Components.

It is described in depth here: https://developer.salesforce.com/blogs/developer-relations/2017/01/lightning-visualforce-communication.html

There is no need of making REST calls for communication between VF and Lightning or going back to server as crmprgdev describes.

window.postMessage() is also not affected by LockerService. In fact you can find in the documentation of LockerService that this Standard Javascipt API is even officially supported by LockerService:

http://documentation.auraframework.org/lockerApiTest/index.app?aura.mode=DEV

That means all this works fine with v40.0 and chances are very good that it will work in future versions either.