Get parent page to scroll to top when iframe's

2019-08-15 17:48发布

问题:

A client wants to adapt an existing form for their site-wide subscription application. Due to the way the site is laid out, the easiest way to implement this was to have an iframe pull the existing form into the new page. However, this has caused some issues with existing behavior when form validation triggers a fail.

I have an iframe in the page:

<iframe class="contactForm" frameborder="0" height="1720px" 
   src="/path/to/contact.html" width="904px”>

  <p>Your browser does not support frames.</p>

</iframe>

This function triggers on a submit event:

$('form#ContactForm').bind('submit', function(event){ 
    if ( !validation ) {

        var error ="Please fill out the entire form";
        $('#formErrors').text(error);
        $('html,body').animate({
            scrollTop: $("#formErrors").offset().top},
                'fast');
        }
    } else {
        //execute ajax submission here
    }
}

executes. If the form fails validation, a div element at the top of the form page is populated with the error text and a fast scroll action is animated. However, since the iframe is set to a height large enough to accomodate the original form page without any scrolling, this scroll action does not execute.

Is there any way that I can have this scroll action work in a window IF and ONLY IF this script is loaded in an iframe while maintaining the existing behavior on the original page?

回答1:

The solution for this was to use window.postMessage.

In the parent window, I had

function receiveMessage(e){

  console.log("Received Message: " + e);

  if (e.originalEvent.origin === 'http://www.site.client.com') {
    $("html, body").animate({
        scrollTop : 441
    }, "fast");
  }
}
$(window).bind("message", receiveMessage);

and added this for the original js code for the iframe content:

window.parent.postMessage("Scroll", "http://www.site.client.com/");

This results in the iframe posting a message that is captured by the parent. Since this is the only message posted, I use it to trigger the scroll event if and only if the domains match.



回答2:

$('form#ContactForm').bind('submit', function(event){ 
    if ( !validation ) {

        var error ="Please fill out the entire form";
        $('#formErrors').text(error);
        if (window.top != window) {
            $('html,body').animate({
                scrollTop: $("#formErrors").offset().top},
                    'fast');
            }
        }
    } else {
        //execute ajax submission here
    }
}