简体   繁体   中英

Can it be determined if window.resizeTo will work?

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?

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
}

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

MDN is a great JavaScript resource: https://developer.mozilla.org/en-US/docs/Web/API/Window.resizeTo

Since Firefox 7, it's no longer possible for a web site to change the default size of a window in a browser, according to the following rules:

You can't resize a window or tab that wasn't created by window.open .

You can't resize a window or tab when it's in a window with more than one tab.

SO, you need to detect if you are a child window:

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

if (window.opener) { 
  console.log('I can be resized'); 
} else { 
    console.log('I cannot be resized'); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM