JSFiddle - React, Tailwind, and code Playground

by Dylan Schadeck

JavaScript

/**
 * function to get authentication information
 * from the FOX nation site
 */
var getNationAuthInfo = (function() {
  // iframe url - fox nation team will provide
  var IFRAME_SRC = 'https://try.nation.foxnews.com/js/nation-xdcomm/',
  //var IFRAME_SRC = 'https://qa-nation.foxnews.com/account/static/test/nation-xdcomm.html',
    messageId = 'nation.xdcomm.frame',
    initialized = false;

  return function(callback) {
    if (typeof callback !== 'function') {
      return;
    }

    // listener - only set once
    (function() {
      if (initialized) {
        return;
      }
      initialized = true;

      var handler = function(payload) {
        var data = payload && payload.data ? payload.data : null,
          info = data && data.data ? data.data : null;

        if (data && data.type === messageId) {
          callback(info);
        }
      };

      try {
        window.addEventListener('message', handler, false);
      } catch (error) {
        window.attachEvent('onmessage', handler);
      }
    })();

    // insert iframe
    (function(d) {
      var id = 'nation-xdcomm-auth';

      var exists = document.querySelector('#' + id);
      if (exists) {
        exists.contentWindow.postMessage(
          {
            type: messageId,
            data: true
          },
          '*'
        );
      } else {
        var ifr = document.createElement('iframe');
        ifr.src = IFRAME_SRC;
        ifr.setAttribute('id', id);
        ifr.setAttribute('border', 0);
        ifr.setAttribute('frameborder', 0);
        ifr.setAttribute('scrolling', 'no');
        ifr.setAttribute('style', 'width:0%;height:0;display:none;');

        document.addEventListener('DOMContentLoaded', function(event) {
          document.querySelector('body').append(ifr);
        });
      }
    })();
  };
})();


// example call
getNationAuthInfo(function(info){
  // alert('see console.log');
  console.log('payload ---', info);
});