使用postMessage()方法将一个HTML块发送到另一个URL

3

目标:复制一段HTML代码并将其发送至另一个域名的网站。

问题:我正在处理的网站和iframe中的网站位于不同的域。我拥有它们两个,并设置了Access-Control-Allow-Origin以允许网站相互通信。然而,我似乎无法将HTML代码块传递到父窗口。
我尝试了parent.window.postMessage(chunk, http://www.parent-page.com)(chunk是HTML代码块),但是我收到了这个错误消息:
Uncaught DataCloneError: Failed to execute 'postMessage' on 'Window': An object could not be cloned.
我也试图使用ajax向父窗口发送PUT请求,但我收到了一个404错误,表示找不到父窗口。*我从本地服务器运行父窗口。

问题:有谁能告诉我在两个不同域上的网站之间从iframe到父窗口发送包含HTML代码的对象的最佳方法?

编辑:我删除了关于骨架对象的内容,因为这超出了我真正要问的问题的范围。


有可靠的方法将其转换为字符串吗? - Sneakyp33t
如果您拥有这两个网站,难道不能通过父级网站来访问子级内容吗? - zer00ne
@zer00ne 我尝试使用 var viewFrame = $('iframe#frame').contents(); 获取子框架的HTML。但我得到了以下错误:Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:63343" from accessing a frame with origin "http://ccook.oegllc.com". Protocols, domains, and ports must match. - Sneakyp33t
@EL45 我已经编辑了我的问题,进一步解释了骨架对象。 - Sneakyp33t
显示剩余5条评论
1个回答

1

我写了以下代码来解决这个问题。欢迎提出建设性的批评意见。

父窗口网站上的代码:

//send a message to the website in the iframe
  $("#frame").on("load", function (event) {
    var viewContainer = $('#element-highlight');
    var iframe = document.querySelector('iframe');
    var receiver = iframe.contentWindow;
    var location = 'http://www.child-website.com';
    event.preventDefault();
    receiver.postMessage("sendStructure",location);   
  });

//listen for a response
  window.addEventListener('message', function(event) { //event = onmessage event object
    if (~event.origin.indexOf('http://ccook.oegllc.com')) { //indexOf returns a -1 if the searchValue is not found    
      var structure = event.data;
    var container = document.getElementById("element-highlight");
    container.innerHTML = structure;
    }
  }
<script src="../jquery/3.0.0/jquery.min.js"></script>
<body>
  <div id="frame-container">
        <iframe id="frame" src="http://www.main-site.com" frameborder="0"></iframe>
        <div id="element-highlight">
          <!-- Store Skeleton Copies here -->
        </div>
</div>
  
</body>

在iframe中显示的网站上的代码:

我无法让下面的case语句看起来更好。

        //listen for command from main-site.com
        window.addEventListener('message', function(event) { //event = onmessage event object
            if (~event.origin.indexOf('http://www.main-site.com')) { //indexOf returns a -1 if the searchValue is not found
                switch(event.data){
                    case "sendStructure":
                   var structure = getStructure(),
                      tempNode = document.createElement("div");
                      structure.appendTo(tempNode); //appends structure to html document
       var str = tempNode.innerHTML; //creates a serilized version of the structure
       parent.window.postMessage(str, event.origin); //send structure string to main-site.com
     break;
    //I reccomend using a case statement if the two sites will be sending more than one message to each other
                    default:
                        sendError();
                }
            }

        });


        function getStructure(){
            //this method creates a skeleton of the course page you are on
            //returns a skeleton object
            console.log("compiling structure");
            var viewFrame = $('body').contents(); //<-change 'body' to whatever element you want to copy
            var visible = viewFrame.find('*:not(html body)').filter(':visible');
            var overlayElements = visible.map(function (i, el) {
                    var el = $(el);
                    var overlayEl = $('<div>');

                    overlayEl.addClass('highlight').css($.extend({
                        position: 'absolute',
                        width: el.outerWidth(),
                        height: el.outerHeight(),
                        'z-index': el.css('z-index')
                    }, el.offset()));

                return overlayEl.get();
                });
          
        return overlayElements;
        }

        function sendError(){
            console.log("main-website's request could not be understood");
        }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接