CHROME扩展笔记之获取网站根域名

/**
* 获取网站的根域名
*/
function getMainHost() {
     
  var key  = 'author_'+Math.random();
  var keyR = new RegExp( '(^|;)\\s*'+key+'[email protected]' );
  var expiredTime = new Date( 0 );
  var domain = document.domain;
  var domainList = domain.split( '.' );

  var urlItems   = [];
  // 主域名一定会有两部分组成
  urlItems.unshift( domainList.pop() );
  // 慢慢从后往前测试
  while( domainList.length ) {
     
    urlItems.unshift( domainList.pop() );
    var mainHost = urlItems.join( '.' );
    var cookie = key+'[email protected];domain=.'+mainHost;
    document.cookie = cookie;

    //如果cookie存在,则说明域名合法
    if ( keyR.test( document.cookie ) ) {
     
      document.cookie = cookie+';expires='+expiredTime;
      return mainHost;
    }
  }
}

你可能感兴趣的:(es6,javascript,前端,chrome,javascript,es6/es7)