Resize a cross area iFrame (the hackiest approach)

State of affairs 🤔

A while in the past, I used to be implementing a cross area iFrame in Subsequent.js and ran right into a slight downside when it got here to dynamically setting its top. As a consequence of limitations imposed by the browser, we’re prevented from utilizing JS magic to entry the web page and getting the precise top of the doc. A library, iframe-resizer promised to unravel the difficulty nonetheless it required a small script to be positioned on the web page internet hosting the iFrame. Sadly that wasn’t an possibility 🚫

Job 📃

Happily, at two redbulls deep, Poros had mercy and an ✨concept✨ got here outta no the place. What I wished to perform was, on web page load, assign a top to the iFrame that can show all it is contents with out unneeded whitespace. Why not do it in essentially the most straight ahead approach doable? Remotely load the URL that can get displayed within the iFrame, get the peak of the loaded contents then apply that top to the iFrame.

Lights, Digicam… Motion! 🎬

A method to do that was by means of browser automation. There’s Selenium however I went with Puppeteer. I made an API endpoint that when hit, makes use of Puppeteer to load the positioning then get & return the peak utilizing this method I saw on stackoverflow.

Outcomes 💯

The outcome was a web page that takes slightly longer to load however has an iFrame that accurately exhibits all of the contents! Try the code pattern beneath

// npm i puppeteer
const puppeteer = require('puppeteer')

async perform getContentHeight({ clientWidth, clientHeight }) {
    const browser = await puppeteer.launch({ headless: true });
    const web page = await browser.newPage();
    await web page.setViewport({ width: clientWidth, top: clientHeight })
    await web page.goto('my-url-was-here-b4-yours');
    const contentHeight = await web page.consider(() => {
        let physique = doc.physique,
            html = doc.documentElement;

        let top = Math.max(physique.scrollHeight, physique.offsetHeight,
            html.clientHeight, html.scrollHeight, html.offsetHeight);
        return top

    await browser.shut();

getContentHeight({ clientWidth: 1366, clientHeight: 768 })
Enter fullscreen mode

Exit fullscreen mode


Pleaaase do not use this in prod! However, when you do.. let me know the way it goes 😂


Cowl picture: Andy Park Art

Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.

Checkout extra Articles on Sayed.CYou

#Resize #cross #area #iFrame #hackiest