CHROME扩展笔记之获取网站根域名
/** * 获取网站的根域名 */ function getMainHost() { var key = 'author_'+Math.random(); var keyR = new RegExp( '(^|;)\\s*'+key+'=slongzhang@qq.com' ); 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+'=slongzhang@qq.com;domain=.'+mainHost; document.cookie = cookie; //如果cookie存在,则说明域名合法 if ( keyR.test( document.cookie ) ) { document.cookie = cookie+';expires='+expiredTime; return mainHost; } } }