Skip to content

Instantly share code, notes, and snippets.

@gauravtiwari
Last active December 5, 2024 18:40
Show Gist options
  • Select an option

  • Save gauravtiwari/2ae9f44aee281c759fe5a66d5c2721a2 to your computer and use it in GitHub Desktop.

Select an option

Save gauravtiwari/2ae9f44aee281c759fe5a66d5c2721a2 to your computer and use it in GitHub Desktop.

Revisions

  1. gauravtiwari revised this gist Nov 19, 2016. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions window-auth-popup.es6.js
    Original file line number Diff line number Diff line change
    @@ -45,3 +45,14 @@ const popup = (url) => {
    };

    export default popup;

    // On Server view after response
    window.opener.postMessage(
    { auth: { token: access_token } },
    window.opener.location
    );

    window.opener.postMessage(
    { error: 'Login failed' },
    window.opener.location
    );
  2. gauravtiwari created this gist Nov 19, 2016.
    47 changes: 47 additions & 0 deletions window-auth-popup.es6.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    /* global window */

    const popup = (url) => {
    const windowArea = {
    width: Math.floor(window.outerWidth * 0.8),
    height: Math.floor(window.outerHeight * 0.5),
    };

    if (windowArea.width < 1000) { windowArea.width = 1000; }
    if (windowArea.height < 630) { windowArea.height = 630; }
    windowArea.left = Math.floor(window.screenX + ((window.outerWidth - windowArea.width) / 2));
    windowArea.top = Math.floor(window.screenY + ((window.outerHeight - windowArea.height) / 8));

    const sep = (url.indexOf('?') !== -1) ? '&' : '?';
    const url = `${url}${sep}`;
    const windowOpts = `toolbar=0,scrollbars=1,status=1,resizable=1,location=1,menuBar=0,
    width=${windowArea.width},height=${windowArea.height},
    left=${windowArea.left},top=${windowArea.top}`;

    const authWindow = window.open(url, 'producthuntPopup', windowOpts);
    // Create IE + others compatible event handler
    const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
    const eventer = window[eventMethod];
    const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';

    // Listen to message from child window
    const authPromise = new Promise((resolve, reject) => {
    eventer(messageEvent, (e) => {
    if (e.origin !== window.SITE_DOMAIN) {
    authWindow.close();
    reject('Not allowed');
    }

    if (e.data.auth) {
    resolve(JSON.parse(e.data.auth));
    authWindow.close();
    } else {
    authWindow.close();
    reject('Unauthorised');
    }
    }, false);
    });

    return authPromise;
    };

    export default popup;