Issue
In my app, I am loading an iFrame into a modal; the source of the iFrame is my server. The iframe content loads properly, but I am trying to get the parent window and the child window to talk to each other and am getting the following error:
Blocked a frame with origin "https://api.myappdomain.com" from access a cross-origin frame
In the controller, when the modal loads I am initiating the following:
function iFrameMsg(d) {
console.log(d.data) ;
}
$scope.modalOpen = function() {
window.document.addEventListener('iframeMsg', iFrameMsg, false) ;
$scope.iframeModal.show() ;
}
And in the modal template:
<iframe ng-src="https://myappdomain.com/content/index.html"></iframe>
And in index.html
on the server is the following scripts:
<script>
function sendMsg(data) {
var event = new CustomEvent('iframeMsg', { data: data }) ;
window.parent.document.dispatchEvent(event) ;
}
</script>
And in the page a test button:
<button onclick="sendMsg({'some': 'data value'});"> This is a button </button>
Clicking the button to send a message back to the parent generates the error. Is there something I need to add to my app, or the web page, to allow the communication to work between iframe server page and the app parent window? Or will this technique not work at all? If not, what would work then?
Solution
You can use the postMessage API to send messages between your Cordova app and the web page in an iframe:
Cordova app:
// Listen for messages from child frames
const onFrameMessage = (event) => {
const name = event.data[0],
data = JSON.parse(event.data[1]);
};
window.addEventListener('message', onFrameMessage, false);
// Send message to child frame
const postMessageToiFrame = (name, data) => {
iframe.contentWindow.postMessage([name, JSON.stringify(data)], "https://your.server.domain");
};
Webpage in iframe
// Listen for messages from Cordova app
const onFrameMessage = (event) => {
const data = event.data;
};
window.addEventListener('message', onFrameMessage, false);
// Send message to Cordova app
const postMessageToApp = (name, data) => {
window.parent.postMessage([name, JSON.stringify(data)], "*");
}
Answered By - DaveAlden
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.