clumsyjedi
clumsyjedi

Reputation: 507

Scrolling a parent document from within an iframe

I have two documents like this:

http://mydomain/nsobd.html

<html>
    <body>
        <p name="parentElem" id="parentElem">No sign of Big Dave</p>
        <iframe src="http://subdomain.mydomain/nsobd2.html"></iframe>
    </body>
</html>

http://subdomain.mydomain/nsobd2.html

<html>
    <body>
        <a href="???" id="childLink">No sign of Big Dave</a>
    </body>
</html>

What I want, is when someone clicks the childLink in the iframe, the parentElem scrolls into view.

I have tried:

  1. Using <a href="#parentElem" target="_parent"> - this loads http://subdomain.mydomain/nsobd2.html#parentElem in the parent frame.
  2. Using <a href="javascript:document.findElementById('parentElem').scrollIntoView()"> - this does not work due to the two documents being on different subdomains.

Any other ideas?

Upvotes: 0

Views: 1172

Answers (1)

Marco L&#252;thy
Marco L&#252;thy

Reputation: 1309

Since you're trying to communicate between two domains, the short answer is you can't. You can't because of restrictions put in place at the browser level to prohibit cross-site-scripting.

For instance, imagine I registered the domain superwinningcontest.com and sent out links to people's emails. When they loaded up the main page, I could hide a few iframes in there and read their Facebook feed, check recent Amazon or PayPal transactions, or--if they used a service that did not implement sufficient security--transfer money out of their accounts. That's why JavaScript is limited to same-domain and same-protocol. [source]

However, you may be able to achieve your goal with cross-document-messaging. The github project porthole may be able to help you. So, instead of calling or executing some function in the parent window from the iframe, you send a message to the parent window "hey, mind scrolling to X?" from the iframe. When parent frame receives this message it can then decide to execute some function which might then scroll to location X.

There seem to be a number of related answers on this StackOverflow thread. For example in this answer a user implements a cross-document-messaging scheme which might work for you.

Upvotes: 1

Related Questions