0

如果服务器上发生异常,我正在尝试从父页面发布 Iframe 数据并重新加载父页面。到目前为止,我已经到达这里,所以这里有什么可以改进的。

脚本:

<script type="text/javascript">
function iframeFunction(value) {
    var iframe = document.getElementById('testiframe');
    var iframeContent = iframe.contentDocument || iframe.contentWindow.document;
    var testMsg = iframeContent.getElementById('testMsg').value; 
    SendIframeData(testMsg);
}

function SendIframeData(testMsg) {
    $.ajax({
        url: "/Test/SendIframeData",
        dataType: "json",
        data: "{'iframeData':{'iframeDataMessage':'" + testMsg + "'}}",
        type: "post",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            //var responseData = $.parseJSON(data);
            //alert(responseData);
            if (data.ServerMessage == "Exception") {
                alert("Exception");
            }
            else {
                alert("Sent Data Successfully!");
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
        }
    });
}
   </script>

父 HTML:

   <div style="margin-top: 50px;">
   <iframe src="/Test/IframePage" id="testiframe" name="testiframe"></iframe>
   <br /><br />
   <button onclick="iframeFunction()">Submit</button>
   </div>

iFrame 页面 HTML:

     `<div>
       <input id="testMsg" value="Hello!" />
      </div>`

其他方法:

<iframe src="http://a.JavaScript.info/files/tutorial/window/receive.html" id="iframe" style="height:60px"></iframe>

   <form name="form">
     <input type="text" name="msg" value="Your message"/>
       <input type="submit"/>
   </form>

    <script>

     var win = document.getElementById("iframe").contentWindow

   document.forms.form.onsubmit = function() {
     win.postMessage(
       this.elements.msg.value,
           "http://a.JavaScript.info" 
       )
            return false
         }

         </script>

接收方:

     <div id="test">Send me a message!</div>
      <script>
      function listener(event){
      if ( event.origin !== "http://javascript.info" )
      return

      document.getElementById("test").innerHTML = "received: "+event.data
      }

   if (window.addEventListener){
    addEventListener("message", listener, false)
  } else {
    attachEvent("onmessage", listener)
  }
 </script>
4

1 回答 1

0

     <head>
            <script type="text/javascript">
                   (function(){var a=false,b=/xyz/.test(function()  {xyz})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(g){var f=this.prototype;a=true;var e=new this();a=false;for(var d in g){e[d]=typeof g[d]=="function"&&typeof f[d]=="function"&&b.test(g[d])?(function(h,i){return function(){var k=this._super;this._super=f[h];var j=i.apply(this,arguments);this._super=k;return j}})(d,g[d]):g[d]}function c(){if(!a&&this.init){this.init.apply(this,arguments)}}c.prototype=e;c.prototype.constructor=c;c.extend=arguments.callee;return c}})();(function(c){var b={trace:function(d){if(c.console!==undefined){c.console.log("Porthole: "+d)}},error:function(d){if(c.console!==undefined){c.console.error("Porthole: "+d)}}};b.WindowProxy=function(){};b.WindowProxy.prototype={post:function(e,d){},addEventListener:function(d){},removeEventListener:function(d){}};b.WindowProxyBase=Class.extend({init:function(d){if(d===undefined){d=""}this.targetWindowName=d;this.origin=c.location.protocol+"//"+c.location.host;this.eventListeners=[]},getTargetWindowName:function(){return this.targetWindowName},getOrigin:function(){return this.origin},getTargetWindow:function(){return b.WindowProxy.getTargetWindow(this.targetWindowName)},post:function(e,d){if(d===undefined){d="*"}this.dispatchMessage({data:e,sourceOrigin:this.getOrigin(),targetOrigin:d,sourceWindowName:c.name,targetWindowName:this.getTargetWindowName()})},addEventListener:function(d){this.eventListeners.push(d);return d},removeEventListener:function(g){var d;try{d=this.eventListeners.indexOf(g);this.eventListeners.splice(d,1)}catch(h){this.eventListeners=[]}},dispatchEvent:function(f){var d;for(d=0;d<this.eventListeners.length;d++){try{this.eventListeners[d](f)}catch(g){}}}});b.WindowProxyLegacy=b.WindowProxyBase.extend({init:function(d,e){this._super(e);if(d!==null){this.proxyIFrameName=this.targetWindowName+"ProxyIFrame";this.proxyIFrameLocation=d;this.proxyIFrameElement=this.createIFrameProxy()}else{this.proxyIFrameElement=null;throw new Error("proxyIFrameUrl can't be null")}},createIFrameProxy:function(){var d=document.createElement("iframe");d.setAttribute("id",this.proxyIFrameName);d.setAttribute("name",this.proxyIFrameName);d.setAttribute("src",this.proxyIFrameLocation);d.setAttribute("frameBorder","1");d.setAttribute("scrolling","auto");d.setAttribute("width",30);d.setAttribute("height",30);d.setAttribute("style","position: absolute; left: -100px; top:0px;");if(d.style.setAttribute){d.style.setAttribute("cssText","position: absolute; left: -100px; top:0px;")}document.body.appendChild(d);return d},dispatchMessage:function(e){var d=c.encodeURIComponent;if(this.proxyIFrameElement){var f=this.proxyIFrameLocation+"#"+d(b.WindowProxy.serialize(e));this.proxyIFrameElement.setAttribute("src",f);this.proxyIFrameElement.height=this.proxyIFrameElement.height>50?50:100}}});b.WindowProxyHTML5=b.WindowProxyBase.extend({init:function(d,e){this._super(e);this.eventListenerCallback=null},dispatchMessage:function(d){this.getTargetWindow().postMessage(b.WindowProxy.serialize(d),d.targetOrigin)},addEventListener:function(e){if(this.eventListeners.length===0){var d=this;this.eventListenerCallback=function(f){d.eventListener(d,f)};c.addEventListener("message",this.eventListenerCallback,false)}return this._super(e)},removeEventListener:function(d){this._super(d);if(this.eventListeners.length===0){c.removeEventListener("message",this.eventListenerCallback);this.eventListenerCallback=null}},eventListener:function(e,d){var f=b.WindowProxy.unserialize(d.data);if(f&&(e.targetWindowName==""||f.sourceWindowName==e.targetWindowName)){e.dispatchEvent(new b.MessageEvent(f.data,d.origin,e))}}});if(typeof c.postMessage!=="function"){b.trace("Using legacy browser support");b.WindowProxy=b.WindowProxyLegacy.extend({})}else{b.trace("Using built-in browser support");b.WindowProxy=b.WindowProxyHTML5.extend({})}b.WindowProxy.serialize=function(d){if(typeof JSON==="undefined"){throw new Error("Porthole serialization depends on JSON!")}return JSON.stringify(d)};b.WindowProxy.unserialize=function(g){if(typeof JSON==="undefined"){throw new Error("Porthole unserialization dependens on JSON!")}try{var d=JSON.parse(g)}catch(f){return false}return d};b.WindowProxy.getTargetWindow=function(d){if(d===""){return top}else{if(d==="top"||d==="parent"){return c[d]}}return parent.frames[d]};b.MessageEvent=function a(f,d,e){this.data=f;this.origin=d;this.source=e};b.WindowProxyDispatcher={forwardMessageEvent:function(i){var g,h=c.decodeURIComponent,f,d;if(document.location.hash.length>0){g=b.WindowProxy.unserialize(h(document.location.hash.substr(1)));f=b.WindowProxy.getTargetWindow(g.targetWindowName);d=b.WindowProxyDispatcher.findWindowProxyObjectInWindow(f,g.sourceWindowName);if(d){if(d.origin===g.targetOrigin||g.targetOrigin==="*"){d.dispatchEvent(new b.MessageEvent(g.data,g.sourceOrigin,d))}else{b.error("Target origin "+d.origin+" does not match desired target of "+g.targetOrigin)}}else{b.error("Could not find window proxy object on the target window")}}},findWindowProxyObjectInWindow:function(d,g){var f;if(d.RuntimeObject){d=d.RuntimeObject()}if(d){for(f in d){if(d.hasOwnProperty(f)){try{if(d[f]!==null&&typeof d[f]==="object"&&d[f] instanceof d.Porthole.WindowProxy&&d[f].getTargetWindowName()===g){return d[f]}}catch(h){}}}}return null},start:function(){if(c.addEventListener){c.addEventListener("resize",b.WindowProxyDispatcher.forwardMessageEvent,false)}else{if(document.body.attachEvent){c.attachEvent("onresize",b.WindowProxyDispatcher.forwardMessageEvent)}else{b.error("Cannot attach resize event")}}}};if(typeof c.exports!=="undefined"){c.exports.Porthole=b}else{c.Porthole=b}})(this);
            </script>

    <script type="text/javascript">
        var guestDomain = 'demo.auberger.com';

        function onMessage1(messageEvent) {  
            if (messageEvent.origin == "http://" + guestDomain) {
                if (messageEvent.data["color"]) {
                    document.body.bgColor = messageEvent.data["color"];
                }
                if (messageEvent.data["expanded"]) {
                    el = document.getElementById('guestFrame1');
                    el.setAttribute('height', "250px");
                } else {
                    el = document.getElementById('guestFrame1');
                    el.setAttribute('height', "150px");
                }
            }
        }

        /*
            Use a different message handler for the 2nd window so we can customize the meaning of expand/collapse
            messages for instance.
        */
        function onMessage2(messageEvent) { 
            if (messageEvent.origin == "http://" + guestDomain) {
                if (messageEvent.data["color"]) {
                    document.body.bgColor = messageEvent.data["color"];
                }
                if (messageEvent.data["expanded"]) {
                    el = document.getElementById('guestFrame2');
                    el.setAttribute('width', "600px");
                } else {
                    el = document.getElementById('guestFrame2');
                    el.setAttribute('width', "500px");
                }
            }
        }

        var windowProxy1, windowProxy2;
        window.onload=function(){ 
                // Create a proxy window to send to and receive message from the guest iframe
                windowProxy1 = new Porthole.WindowProxy('http://' + guestDomain + '/porthole/proxy.html', 'guestFrame1');
                windowProxy1.addEventListener(onMessage1);

                // Create a proxy window to send to and receive message from the guest iframe
                windowProxy2 = new Porthole.WindowProxy('http://' + guestDomain + '/porthole/proxy.html', 'guestFrame2');
                windowProxy2.addEventListener(onMessage2);
        };
    </script>
</head>
<body>
    <p>
        This is content inside the parent window.
    </p>
    <p>
        Click a button to communicate with the child frames.
    </p>
    <div>
        <input onclick="windowProxy1.post({'color':'red'})" type="submit" value="Color Frame1 Red" /> 
        <input onclick="windowProxy2.post({'color':'yellow'})" type="submit" value="Color Frame2 Yellow" />
    </div>
    <div>
        <h3>Frame 1</h3>
        <iframe id="guestFrame1" name="guestFrame1" width="500px" height="150px" frameborder="1" src="http://demo.auberger.com/porthole/" scrolling="no"></iframe>
    </div>
    <div>
        <h3>Frame 2</h3>
        <iframe id="guestFrame2" name="guestFrame2" width="500px" height="150px" frameborder="1" src="http://demo.auberger.com/porthole/" scrolling="no"></iframe>
    </div>
</body>

于 2013-10-28T11:16:36.570 回答