It is easy to open a new window in javascript, example you just use
window.open(‘https://dawud135.wordpress.com/’, ‘_newwindow’, ‘width=480px,height=500px,toolbar=no,menubar=no,scrollbars=no,location=no,directories=no’);
but this new window is open not in the center of the browser. So to make every new window is centered we need to overwrtie this window.open function, calculate the window width and height and then adjust the new window position.
This is what i use to achieve it:
// function to overwrite the window.open so the opened window is in the middle of the window parent
window.open = function (open) {
return function (url, title, params) {
// set name if missing here
title = title|| "default_window_name";
var w = 480, // default width
h = 640, // default height
arr_other_params = [];
var arr = params.split(‘,’);
for (var idx in arr) {
var row = arr[idx].split(‘=’);
if (row.length == 2) {
if (row[0] == ‘width’) {
w = row[1];
} else if (row[0] == ‘height’) {
h = row[1];
} else if (row[0] == ‘left’ || row[0] == ‘top’) {
//do nothing, overwrite these later
} else {
arr_other_params.push(row[0] + ‘=’ + row[1]);
}
}
}
var userAgent = navigator.userAgent,
mobile = function () {
return /\b(iPhone|iP[ao]d)/.test(userAgent) ||
/\b(iP[ao]d)/.test(userAgent) ||
/Android/i.test(userAgent) ||
/Mobile/i.test(userAgent);
},
screenX = typeof window.screenX != ‘undefined’ ? window.screenX : window.screenLeft,
screenY = typeof window.screenY != ‘undefined’ ? window.screenY : window.screenTop,
outerWidth = typeof window.outerWidth != ‘undefined’ ? window.outerWidth : document.documentElement.clientWidth,
outerHeight = typeof window.outerHeight != ‘undefined’ ? window.outerHeight : document.documentElement.clientHeight – 22,
targetWidth = mobile() ? null : w,
targetHeight = mobile() ? null : h,
V = screenX < 0 ? window.screen.width + screenX : screenX,
left = parseInt(screenX + (outerWidth – targetWidth) / 2, 10),
right = parseInt(screenY + (outerHeight – targetHeight) / 2.5, 10),
features = [];
if (targetWidth !== null) {
features.push(‘width=’ + targetWidth);
}
if (targetHeight !== null) {
features.push(‘height=’ + targetHeight);
}
features.push(‘left=’ + left);
features.push(‘top=’ + right);
for (var i in arr_other_params) {
features.push(arr_other_params[i]);
}
// return PopupCenter(url, title, w, h, other_params);
var newWindow = open.call(window, url, title, features.join(‘,’));
if (window.focus) {
newWindow.focus();
}
return newWindow;
};
}(window.open);