prem prem - 2 months ago 15
Javascript Question

scrolling iframe with parent window

How to scroll the parent window together with scrolling the iframe.I mean to say if someone scroll the iframe it should scroll the parent window as well. I am thinking to achieve this by javascript. The origins are the same.

Answer

Since your two documents share the same origin you are not restricted by the same origin policy, meaning that you can just call from javascript in one document to javascript in the other document.

A simple example:

The parent index.html

<html>
    <head>
        <script>
            function handleMessage(msg) {
                console.log("message from iframe: ", msg);
            }

            function sendMessage() {
                let msg = {
                    value: document.getElementById("message").value
                }

                document.getElementById("iframe").contentWindow.handleMessage(msg);
            }
        </script>
    </head>
    <body>
        <input type="text" id="message" />
        <button onclick="sendMessage()">send message to parent</button>
        <br/><br/>
        <iframe id="iframe" src="iframe.html"></iframe>
    </body>
</html>

The iframe.html

<html>
    <head>
        <script>
            function handleMessage(msg) {
                console.log("message from parent: ", msg);
            }

            function sendMessage() {
                let msg = {
                    value: document.getElementById("message").value
                }

                parent.handleMessage(msg);
            }
        </script>
    </head>
    <body>
        <input type="text" id="message" />
        <button onclick="sendMessage()">send message to parent</button>
    </body>
</html>

Now that you know how to call js methods from one document to the other, it should be simple enough to catch scrolling events in one and then let the other know about the scroll delta.

Comments