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

后端 未结 5 1304
野趣味
野趣味 2020-12-08 09:50

When someone clicks on a link within an iframe (child page), how do I get the parent page to scroll to the top? The issue is the child page will remain in the same spot of t

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 10:16

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

提交回复
热议问题