使用postMessage()

时间:2016-07-18 21:30:26

标签: javascript jquery html iframe

目标:复制一大块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错误,它无法找到父窗口。 *我正在从本地服务器运行父窗口
我的问题:任何人都可以告诉我将包含HTML代码的对象从iframe发送到父窗口的最佳方式,因为这两个网站不在同一个域中吗?

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

1 个答案:

答案 0 :(得分:0)

以下是我为解决这个问题所写的内容。任何建设性的批评都是受欢迎的。

父窗口网站上的代码:

//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中显示的网站上的代码:

我无法让下面的案例陈述更好看。

        //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");
        }