Jyina
Jyina

Reputation: 2892

How to implement iFrame communication to prevent from cross origin error?

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>

Upvotes: 0

Views: 4799

Answers (1)

nipunasudha
nipunasudha

Reputation: 2607

This is a security feature in iFrames not to allow hijacking if the domain doesn't allow. this Stack Overflow answer gives a good explanation...

You need control over the domain you want to embed to remove/amend its CORS policy. It the domain has explicitely blocked Cross-Origin requests, there's nothing you can do about it.

This is used to avoid anyone hijacking any site you want (you could have a full screen Google in an iframe running with your ads on top on bettergoogle.com, things like that).


Edit:

To overcome this, either you have to host the webpage with the iframe in the third party domain. or you can request the third party domain owner to enable CORS for a specific domain address (your hosting domain).

Upvotes: 2

Related Questions