How do I Scroll parent page to top when child page is click within iframe?

我是研究僧i 提交于 2019-11-28 06:14:50
Evan

The trick is to append the following onload="window.parent.parent.scrollTo(0,0)" to the iframe and that should do it!

Using JavaScript within the iframe, reference the parent and call the scroll() method.

window.parent.scroll(0,0);
Doaa

If you have cross origins (the iframe and the parent have different domains), then just calling window.scrollTo(0,0) won't work.

One solution to cross-origin is to send a trusted message from the iframe to the parent.

Code inside the iframe:

var parent_origin = 'http://your/iframe/domain/here'
parent.postMessage({'task': 'scroll_top'}, parent_origin);

Then code in the parent:

function handleMessage(event) {
    var accepted_origin = 'http://your/iframe/domain/here';
    if (event.origin == accepted_origin){
        if (event.data['task'] == 'scroll_top'){
           window.scrollTo(0,0);
        }
        // you can have more tasks
    } else{
        console.error('Unknown origin', event.origin);
    }
}

window.onload = function() {
    window.addEventListener("message", handleMessage, false);
}

Within the Iframe page.

window.parent.ScrollToTop(); // Scroll to top function

On The parrent page:

window.ScrollToTop = function(){
  $('html,body', window.document).animate({
    scrollTop: '0px'
  }, 'fast');
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!