SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Author - Kiran Preet
5.09.2017
|
0 Comments
|

Error: Blocked a frame with origin “http://xxx.xxx.xxx.xxx” from accessing a frame with origin “http://xxxxx:xxx”. Protocols, domains, and ports must match.

Scenario: We have a cakephp website. In one webpage say “Parent Page” of this website we have used iframe to show some content from another website/domain say “Child page”. From the “Child Page” that is inside the iframe we need to call javascript function of “Parent Page” webpage.

Initially, we have used window.parent.functionname() in javascript but it shows above error as both the website are different and it restricts the access due to security reasons.

Solution: For resolving this problem we have used parent.postMessage:

In “Child page” within iframe 
parent.postMessage("message","*");
In “Parent page” 
window.addEventListener('message', function(event) { 
// IMPORTANT: Check the origin of the data! 
if (~event.origin.indexOf('http://104.236.210.119')) {   // The data has been sent from your site 
// The data sent with postMessage is stored in event.data 
console.log("origin"+event.data);
} else { 
// The data hasn't been sent from your site! 
// Be careful! Do not use it. 
return; 
} 
});

Explanation:

windowname.postmessage(message,targetOrigin,[transfer]);

Windowname: This is the reference to another window. Use parent in case of communication between iframe and parent window.

Message: This is the data which we send to other window. You can pass broad variety of data using post message because the data within post message is serialized using “The structured Clone algorithm”.

targetOrigin: This is the address or the origin of other window. Use * if you are not sure about the origin.

Transfer [Optional]: This is a sequence of transferable objects that are transferred with the message.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message