Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the page, because the iframe has a lot of height larger than the parent page.

Please note: the parent and child pages are on different sub domains.

I created a demo to show this: http://www.apus.edu/_test/iframe/index.htm

like image 611
Evan Avatar asked Jun 17 '10 19:06

Evan


2 Answers

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

like image 84
Evan Avatar answered Oct 13 '22 11:10

Evan


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); } 
like image 42
Doaa Avatar answered Oct 13 '22 10:10

Doaa