Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can it be determined if window.resizeTo will work?

Tags:

javascript

Inside the Javascript console, if I execute:

m = window.open(location.origin);
m.resizeTo(400, 400);

The window will resize, but if I just execute:

window.resizeTo(400, 400);

then nothing happens. I understand the reason for this behavior. How can I detect situations where window.resizeTo will do nothing?

like image 631
Joseph Lennox Avatar asked Jun 26 '14 16:06

Joseph Lennox


2 Answers

Approach 1:

You can use the window.opener property. If it's null, then you did not open that window and thus cannot resize it.

window.parent is intended more for iframes and the like.

Such as:

if (m.opener) {
    m.resizeTo(400, 400);
} else {
    // You did not create the window, and will not be able to resize it.
}

Approach 2:

ajp15243 brings up a good point, so one thing you could do is listen to the resize event and see if your resizeTo worked:

var resizeFired = false;
...
var triggeredResize = function() {
    resizeFired = true;

    m.removeEventListener('resize', triggeredResize);
}

m.addEventListener('resize', triggeredResize, true);

m.resizeTo(400, 400);

if (resizeFired) {
    // Your resize worked.
}

I haven't been able to fully test this, but it's one potential approach nonetheless. For IE8 and below you may need to use attachEvent instead. Also as @Wesabi noted, the resize may fire for other events (and may fire if the user is resizing the window as the listener as attached), so it's best to execute this is the shortest time span possible.

Approach 3:

Another approach would be to call m.resizeTo(400, 400) and then check the window size to see if the current size is equal to what you set it to:

m.resizeTo(400, 400);
if (w.outerWidth != 400 && w.outerHeight != 400) {
   // Your resize didn't work
}
like image 110
Igor Avatar answered Oct 09 '22 01:10

Igor


The easiest thing to do would be checking if the window has a parent. if !window.parent, it means it's the main window which cannot be resized with JS, else you have your resize case.

Edit: Igor posted it before I found it: you want m.opener() not window.parent

like image 1
Sterling Archer Avatar answered Oct 09 '22 01:10

Sterling Archer