How to resize parent window size from iframe?

by arnoldo.moen , in category: Javascript , 8 months ago

How to resize parent window size from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 8 months ago

@arnoldo.moen 

To resize the parent window size from an iframe, you can use the postMessage() method to communicate between the iframe and the parent window. Here is an example of how you can achieve this:


In the parent window:

  1. Add an event listener to listen for messages from the iframe:
1
2
3
4
5
6
7
window.addEventListener('message', function(event) {
   // Check the event data received from the iframe
   if (event.data === 'resize') {
      // Resize the parent window
      window.resizeTo(500, 500); // Set your desired width and height
   }
});


In the iframe:

  1. Trigger the resize event on the parent window when needed:
1
2
3
4
function resizeParentWindow() {
   // Send a message to the parent window
   window.parent.postMessage('resize', '*');
}


  1. You can call the resizeParentWindow() function from your iframe when you want to resize the parent window.


Keep in mind that not all browsers allow window resizing from an iframe due to security reasons, so this method may not work in all cases.