I am trying to send a http request to a third party API through an iframe to overcome the issue with cross origin error "origin not found in access-control-allow-origin"
The third party API does not return Origin in the response header and they don't accept JSONP http request either so I am trying to implement this using iFrame. I am testing simple html forms to see if it works. Below I have Parent and Child html. My web application owns both Parent and Child. The parent sends a message to child using postMessage and then child makes a GET request to the specified url and tries to post the response to parent.
When I run this, I see the response in network tab from the third party but the browser is still preventing to send it to the iFrame (child.html). Can anyone point out what I am missing here? I think I need to target the iFrame to be same domain as the third party. Thank you for any advice.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>postMessage Demo: Parent</title>
<script type="text/javascript">
window.onload = function () {
var receiver = document.getElementById("ifrmChild").contentWindow;
var btn = document.getElementById('send');
function sendMessage(e) {
e.preventDefault();
receiver.postMessage('https://test.computing.com/my-pay/MyPay.do?UserID=8888&Amount=100&Name=Test', '*');
}
btn.addEventListener('click', sendMessage);
function ReceiveMessage(evt) {
alert(evt.data);
}
window.addEventListener("message", ReceiveMessage, false);
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="receiver.html" frameborder="0" width="500" height="200">
</iframe>
<br />
<p>
<button id="send">Send Message</button>
</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Child</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var messageEle = document.getElementById('message');
function receiveMessage(evt) {
messageEle.innerHTML = "Message Received: " + evt.data;
$.ajax({
url: evt.data,
type: 'GET',
success: function (data, textStatus, jqXHR) {
console.log(data);
evt.source.postMessage(data, "*");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + " " + errorThrown);
evt.source.postMessage(textStatus, "*");
}
});
}
// Setup an event listener that calls receiveMessage() when the window
// receives a new MessageEvent.
window.addEventListener('message', receiveMessage);
}
</script>
</head>
<body style="background-color: gray;">
<h1>Receiver</h1>
<div id="message"></div>
</body>
</html>