最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use JavaScript to access cross domain iFrame content? - Stack Overflow

programmeradmin4浏览0评论

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 ing from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?

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 ing from the same domain, but not for sites from another domain loaded in the iFrame. How can I do it?

Share Improve this question edited Feb 6, 2011 at 10:21 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Feb 6, 2011 at 10:12 monkey_boysmonkey_boys 7,34823 gold badges59 silver badges82 bronze badges 1
  • 1 possible duplicate of Cross Domain URL Access from Iframe using Javascript – biesior Commented Dec 8, 2012 at 10:39
Add a ment  | 

6 Answers 6

Reset to default 4

You can implement window.postMessage to municate 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./" 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./2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/


            // http://stackoverflow./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.")
            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-pliant");
                // For standards-pliant web browsers (ie9+)
                window.addEventListener("message", ReceiveMessage, false);
            }
            else {
                //alert("not standards-pliant (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./" 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/en-US/docs/Web/API/window.postMessage
        // http://ejohn/blog/cross-window-messaging/
        // http://benalman./projects/jquery-postmessage-plugin/
        // http://benalman./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.")
            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-pliant");
                // For standards-pliant web browsers (ie9+)
                window.addEventListener("message", ReceiveMessage, false);
            }
            else {
                //alert("not standards-pliant (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>

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 pletely 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.

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.

Due to same origin policy restrictions this is not allowed.

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

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

发布评论

评论列表(0)

  1. 暂无评论