1

I would like to use this code

window.parent.document.getElementById('message').value  += "\r\n\r\n[img]"+response+"[/img]";

It works fine for pages coming from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
monkey_boys
  • 7,108
  • 22
  • 58
  • 82
  • 1
    possible duplicate of [Cross Domain URL Access from Iframe using Javascript](http://stackoverflow.com/questions/1378433/cross-domain-url-access-from-iframe-using-javascript) – biesior Dec 08 '12 at 10:39

6 Answers6

3

You can implement window.postMessage to communicate accross iframes/windows across domains.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>

    <!--
    <link rel="shortcut icon" href="/favicon.ico">


    <link rel="start" href="http://benalman.com/" title="Home">

    <link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">

    <script type="text/javascript" src="/js/mt.js"></script>
    -->
    <script type="text/javascript">
        // What browsers support the window.postMessage call now?
        // IE8 does not allow postMessage across windows/tabs
        // FF3+, IE8+, Chrome, Safari(5?), Opera10+

        function SendMessage()
        {
            var win = document.getElementById("ifrmChild").contentWindow;

            // http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/


            // http://stackoverflow.com/questions/16072902/dom-exception-12-for-window-postmessage
            // Specify origin. Should be a domain or a wildcard "*"

            if (win == null || !window['postMessage'])
                alert("oh crap");
            else
                win.postMessage("hello", "*");
            //alert("lol");
        }



        function ReceiveMessage(evt) {
            var message;
            //if (evt.origin !== "http://robertnyman.com")
            if (false) {
                message = 'You ("' + evt.origin + '") are not worthy';
            }
            else {
                message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
            }

            var ta = document.getElementById("taRecvMessage");
            if (ta == null)
                alert(message);
            else
                document.getElementById("taRecvMessage").innerHTML = message;

            //evt.source.postMessage("thanks, got it ;)", event.origin);
        } // End Function ReceiveMessage




        if (!window['postMessage'])
            alert("oh crap");
        else {
            if (window.addEventListener) {
                //alert("standards-compliant");
                // For standards-compliant web browsers (ie9+)
                window.addEventListener("message", ReceiveMessage, false);
            }
            else {
                //alert("not standards-compliant (ie8)");
                window.attachEvent("onmessage", ReceiveMessage);
            }
        }
    </script>


</head>
<body>

    <iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
    <br />


    <input type="button" value="Test" onclick="SendMessage();" />

</body>
</html>

Child.htm

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>

    <!--
    <link rel="shortcut icon" href="/favicon.ico">


    <link rel="start" href="http://benalman.com/" title="Home">

    <link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">

    <script type="text/javascript" src="/js/mt.js"></script>
    -->

    <script type="text/javascript">
        /*
        // Opera 9 supports document.postMessage() 
        // document is wrong
        window.addEventListener("message", function (e) {
            //document.getElementById("test").textContent = ;
            alert(
                e.domain + " said: " + e.data
                );
        }, false);
        */

        // https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
        // http://ejohn.org/blog/cross-window-messaging/
        // http://benalman.com/projects/jquery-postmessage-plugin/
        // http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html

        // .data – A string holding the message passed from the other window.
        // .domain (origin?) – The domain name of the window that sent the message.
        // .uri – The full URI for the window that sent the message.
        // .source – A reference to the window object of the window that sent the message.
        function ReceiveMessage(evt) {
            var message;
            //if (evt.origin !== "http://robertnyman.com")
            if(false)
            {
                message = 'You ("' + evt.origin + '") are not worthy';
            }
            else
            {
                message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
            }

            //alert(evt.source.location.href)

            var ta = document.getElementById("taRecvMessage");
            if(ta == null)
                alert(message);
            else
                document.getElementById("taRecvMessage").innerHTML = message;

            // http://javascript.info/tutorial/cross-window-messaging-with-postmessage
            //evt.source.postMessage("thanks, got it", evt.origin);
            evt.source.postMessage("thanks, got it", "*");
        } // End Function ReceiveMessage




        if (!window['postMessage'])
            alert("oh crap");
        else {
            if (window.addEventListener) {
                //alert("standards-compliant");
                // For standards-compliant web browsers (ie9+)
                window.addEventListener("message", ReceiveMessage, false);
            }
            else {
                //alert("not standards-compliant (ie8)");
                window.attachEvent("onmessage", ReceiveMessage);
            }
        }
    </script>


</head>
<body style="background-color: gray;">
    <h1>Test</h1>

    <textarea id="taRecvMessage" rows="20" cols="20" ></textarea>

</body>
</html>
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
3

You can if your browser have disabled security, for chrome it's

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security

Update: I'm surprised that people keep devoting it because they consider it harmful, so here I add some additional details for peoples who don't know basics of web security and still try to develop for it.

DON'T use this solution if

  • you are using chrome plugins or apps which are not trusted by you, or

  • you have opened other sites in the chrome, or

  • you have some malicious chrome processes

  • your site is using any external resources.

To make this solution completely safe, configure your firewall to block all connections except one to which you are making CORS connection.

Also, don't use this solution if your connection endpoint isn't trusted.

setec
  • 15,506
  • 3
  • 36
  • 51
  • 2
    I would consider this very harmful and strongly advice to not use this approach. – Nicky Mar 06 '17 at 10:54
  • 2
    @Nicky it is not harmful if you know what are you doing. But thanks for notice, I've added a disclaimer for those who may try cluelessly use this solution. – setec Mar 20 '17 at 08:39
2

Take a look at easyXDM, it's an easy to use library that provides a unified API for several tricks used to enable cross domain messaging, ranging from postMessage to the FIM-trick as a last resort.
This is what is used by major services such as Twitter and Disqus.

Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/10293604) – Davide Pastore Nov 22 '15 at 12:10
  • 1
    @DavidePastore - this is a very complicated matter, and the question is too open ended to be able to provide a succinct answer to. – Sean Kinsey Nov 25 '15 at 21:32
1

Due to same origin policy restrictions this is not allowed.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

As stated, this falls under same origin policy, but there are some tricks that allow limited communication with the iframe. Take a look at http://ajaxify.com/run/crossframe/

leebriggs
  • 3,187
  • 1
  • 20
  • 17
0

You can't. This is called the same origin policy, and prevents javascript accessing content across domains.

tw39124
  • 9,103
  • 2
  • 20
  • 14