Problem capturing event scroll in iframe in iOS Safari browser

Asked

Viewed 75 times

0

I’m having trouble handling the scroll event from an iframe using Javascript/jQuery in the iOS Safari browser.

I was initially trying to catch the scroll event, but it doesn’t work. Searching, I saw that there is the event touchend, as it is implemented in the code below, but also not working.

    <iframe src="doc.html" id="f" style="width: 100%; height: 600px; border: 0;"></iframe>

    <div id="s"></div>

    <script>
        function scroll_handler() {
            if ($(this).scrollTop() >= ($(this).height() - f.height())) {
                $('#s').text('OK');
            }
        }

        var f = $('#f');
        f.ready(function () {
            if ('ontouchstart' in window) {
                $(f.contents()).on('touchend', scroll_handler);
            } else {
                $(f.contents()).scroll(scroll_handler);
            }
        });
    </script>

Does anyone have any idea how I can get the scroll event from an iframe?

Thanks!

1 answer

-1

I believe that the best solution to this problem would be to use the postMessage API.

The own page of this API via MDN contains examples of how to create this communication channel.

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

With this Voce you can send a message to iframe ("ping") to execute some command, and as well as iframe to reply ("pong") to some command sent.

You can also use the Messagechannel API to create this channel more easily.

https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel

I hope I’ve helped!

  • Thanks for the answer. But I couldn’t understand how this API could help with my problem, since I just want to manipulate the scroll event. I have successfully tested my code in Chrome, Edge and IE for Windows, Chrome and Firefox for Linux, and Chrome for Android. Only in Safari on iOS is it not working.

  • Okay. But what I couldn’t figure out then eh? because you do not apply the code you want inside the doc.html instead of leaving its relatively complex code by doing so by Parent window?

  • Hi Caio, I have no control over the content of iframe, so the code should be on the page that contains iframe. The idea is this: I want content to be available only when the user scrolls the iframe to the end (this is what the scroll_handler method does in a simplified way). The problem is in handling the scroll event in Safari browser on iOS, which runs intermittently.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.