Naresh
Naresh

Reputation: 25743

Scrolling a React app embedded in an iframe using iframe-resizer

I have a React app embedded in an iframe using iframe-resizer:

<iframe id="my-frame" src="http://example.com/my-react-app" scrolling="no"></iframe>
<script>iFrameResize({}, 'my-frame')</script>

This is working well in general. However when the embedded React app switches from a tall page to a short page, it is possible for the React app to go out of sight completely. I have to manually scroll to the top of the iframe to see the app again. Is there a way to do this automatically? I saw the scrollTo API in the iframe-resizer docs, but it's not clear to me how to use it. Do I have to change my React app or the page that embeds it? How? If possible, I would prefer not to change the React app at all.

Upvotes: 1

Views: 5731

Answers (3)

Same issue here. I am showing a (slides-section of a) react-app through an iframe, which is placed inside a wordpress site. All the resizing worked just fine, but the iframe would be placed out of screen-view when the react page resized after the first interaction within it.

Using resizeObserver() solved the issue for me.

I added some code to the iframe.js file in my wordpress theme, resulting into this:

iFrameResize({
    log                     : false, // Enable console logging
  
});

//

let myIframeReady = false
let iframeHeightChanges = 0

document.getElementById('my-iframe').onload = function() {
    myIframeReady = true
}

const resizeObserver = new ResizeObserver(entries => {
  if (!myIframeReady ) {
   return false 
  }
  
  if (iframeHeightChanges === 1) {
    document.getElementById('my-iframe').scrollIntoView()
  }
  
  iframeHeightChanges += 1
})

resizeObserver.observe(document.body)

I hope it helps anyone.

Upvotes: 0

David Bradshaw
David Bradshaw

Reputation: 13077

I have now written a React interface to iframe-resizer, which might help with things like this I the future.

https://github.com/davidjbradshaw/iframe-resizer-react

Upvotes: 1

Pranav Kaushik
Pranav Kaushik

Reputation: 203

Hope you are doing well.

Shouldn't the iFrame resize itself to a smaller height when embedded app moves to a smaller page? If that happens, scrollToTop will not be needed in this case.

Provided the embedded app is using iframeResizer.contentWindow.js

Am I missing something?

Upvotes: 1

Related Questions