Skip to content

Instantly share code, notes, and snippets.

@mflorida
Last active April 30, 2023 08:06
Show Gist options
  • Save mflorida/d0acd294c90b6620c0409485b9c564f8 to your computer and use it in GitHub Desktop.
Save mflorida/d0acd294c90b6620c0409485b9c564f8 to your computer and use it in GitHub Desktop.
Open new (popup) window within the bounds of, and centered over, the calling parent window with max dimensions of 1400x900.
/**
* Open a new browser window centered to the parent window.
* @param {string} url - Required URL for popup window
* @param {string} [name] - optional window name
* @param {object} [cfg] - optional config object for window.open parameters
* @returns {*} - returns reference to popup
* @example
*
* // open a 600x400 popup named 'foo' centered over parent window:
* centeredPopup('/page/foo', 'foo', { width: 600, height: 400 });
*
* // open a nameless window that's 100px narrower than parent window:
* centeredPopup('/page/bar', null, { width: window.outerWidth - 100 });
*
*/
export function centeredPopup(url, name, cfg = {}) {
/devmode/.test(window.location.hash) && console.log('centeredPopup');
// browser sniffing? :-/
// const isEdge = /Edg/i.test(window.navigator.userAgent);
// const pixelRatio = window.devicePixelRatio;
const maxWidth = cfg.width || 1400;
const maxHeight = cfg.height || 860;
// keep a 20px pad inside the available screen area
const availWidth = window.screen.availWidth - 40;
const availHeight = window.screen.availHeight - 40;
// constrain dimensions to screen size?
const W = maxWidth > availWidth ? availWidth : maxWidth;
const H = maxHeight > availHeight ? availHeight : maxHeight;
// position new window centered over the parent window
const LEFT = window.screenLeft + (window.outerWidth / 2) - (W / 2);
const TOP = window.screenTop + (window.outerHeight / 2) - (H / 2);
const params = {
...cfg,
location: cfg.location || 'yes',
resizable: cfg.resizable || 'yes',
width: W,
height: H,
left: cfg.left != null ? cfg.left : LEFT,
top: cfg.top != null ? cfg.top : TOP
};
let paramString = Object.entries(params).map(([key, val]) => `${key}=${val}`).join(',');
const popup = window.open(
`${url}`,
name || '_blank',
paramString
);
// is this the only reliable way to ensure proper cross-browser size/placement?
popup.moveTo(params.left, params.top);
popup.resizeTo(params.width, params.height);
return popup;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment