Skip to content

Instantly share code, notes, and snippets.

@abelaska
Created August 16, 2017 11:27
Show Gist options
  • Save abelaska/d6b322d4c0e4c18011585968908edc0e to your computer and use it in GitHub Desktop.
Save abelaska/d6b322d4c0e4c18011585968908edc0e to your computer and use it in GitHub Desktop.
Centered popup window
const show = ({ url }, resolve, reject) => {
const width = Math.max(1000, Math.floor(window.outerWidth * 0.8));
const height = Math.max(630, Math.floor(window.outerHeight * 0.5));
const left = Math.floor(window.screenX + (window.outerWidth - width) / 2);
const top = Math.floor(window.screenY + (window.outerHeight - height) / 8);
const wOptions = [
'toolbar=0',
'scrollbars=1',
'status=0',
'resizable=1',
'location=0',
'menubar=0',
`width=${width}`,
`height=${height}`,
`left=${left}`,
`top=${top}`
].join(',');
let w;
let reply;
let wTimeout;
let gotmessage = false;
const getMessage = e => {
if (!gotmessage) {
if (e.origin !== '/* @echo apiHost */') {
return;
}
if (!e.data) {
reply = { error: { message: 'No data' } };
} else {
reply = e.data;
}
try {
w.close();
} catch (_error) {}
gotmessage = true;
return true;
}
};
const callback = data => {
if (wTimeout) {
clearTimeout(wTimeout);
wTimeout = null;
}
if (window.removeEventListener) {
window.removeEventListener('message', getMessage, false);
} else if (window.detachEvent) {
window.detachEvent('onmessage', getMessage);
} else {
if (document.detachEvent) {
document.detachEvent('onmessage', getMessage);
}
}
if (data.error) {
reject(data.error);
} else {
resolve(data.data);
}
};
if (window.attachEvent) {
window.attachEvent('onmessage', getMessage);
} else if (document.attachEvent) {
document.attachEvent('onmessage', getMessage);
} else {
if (window.addEventListener) {
window.addEventListener('message', getMessage, false);
}
}
w = window.open(url, 'Authorization', wOptions);
if (w) {
w.focus();
wTimeout = setTimeout(function() {
reply = { error: new Error('Timeout') };
try {
w.close();
} catch (_error) {}
}, 5 * 60 * 1000);
const closeChecker = setInterval(function() {
let close = !w;
try {
if (w) {
close = w.closed;
}
} catch (e) {}
if (close) {
clearInterval(closeChecker);
callback(reply || { error: new Error('Window closed') });
}
}, 500);
} else {
callback({ error: new Error('Window blocked') });
}
};
export default show;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment