Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can I open a page in a new browser window and scroll to a specific position?

Why does the following JavaScript script open a new window, but fails to scroll down the page? (Note that I ran this script in the Web Console in Firefox 4.)

w=window.open("http://stackoverflow.com");w.scrollTo(0,150);

How can I open a page in a new browser window and instruct that window to scroll to a specific position?

like image 971
Derek Mahar Avatar asked May 18 '11 19:05

Derek Mahar


2 Answers

I found something interesting on this...

I've always known you can scroll to an anchor with a name -- in fact, that's the way we were all taught. But I just tried to scroll to a div with an id and it worked!

So, for example, if the target page has a div with id="bobo" then the link http://www.example.com/index.php/home#bobo just worked for me.

Perhaps it's flaky behavior on my end. I feel like I would have heard of this before if it were possible. But all I know is I was trying to do the same thing and for whatever reason it's working.

FWIW, the link I'm using is http://www.religionnews.com/index.php?/rnsblog#blog

like image 76
user624385 Avatar answered Nov 14 '22 23:11

user624385


If you own both domains, you can use window.postMessage to communicate the scroll position to the other window.
In one page you make the postMessage, and in the other you add an event listener.

If you need to support older browsers, you can use window.name to transfer some data between windows.

If you don't own both domains, you're out of luck, due to the SOP. It is a built-in protection in browsers to avoid cross domain abuses.

like image 33
Mic Avatar answered Nov 14 '22 22:11

Mic