Skip to content

Instantly share code, notes, and snippets.

@neekey
Created September 4, 2012 02:57
Show Gist options
  • Save neekey/3616043 to your computer and use it in GitHub Desktop.
Save neekey/3616043 to your computer and use it in GitHub Desktop.
跨域iframe自适应高度脚本
/**
* 跨域iframe自适应高度脚本
*/
var Loader = new function(){
var doc = document,body = doc.body,
self = this,
//获取url中的参数
getRequest = function(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"),
r = window.location.search.substr(1).match(reg);
return (r!=null)? unescape(r[2]) : null;
},
//获取配置,script的优先级大于url中的参数
getConfig = function(){
var scripts = doc.getElementsByTagName('script'),
script = scripts[scripts.length - 1];
return function(param){
var p = script.getAttribute(param);
return p? p : getRequest(param);
};
}(),
//代理高度
proxyheight = 0,
//top页frame的id
frameid = getConfig("data-frameid"),
//监听实时更新高度间隔
timer = getConfig("data-timer"),
//模块统计埋点id
modid = getConfig("mod-id"),
//获取代理的url
getProxyuUrl = getConfig("data-proxy"),
//创建代理的iframe
proxyframe = function(){
var el = doc.createElement("iframe");
el.style.display = "none";
el.name="proxy";
return el;
}();
//重置高度
this.resize = function(){
proxyheight = body.offsetHeight;
proxyframe.src = getProxyuUrl + "?data-frameid=" + frameid + "&data-frameheight=" + (proxyheight);
}
this.init = function(){
var init = function(){
body.appendChild(proxyframe);
self.resize();
//是否update
if(!isNaN(timer)){
timer = timer<200? 200: timer;
window.setInterval(function(){
if(body.offsetHeight != proxyheight){
self.resize();
}
},timer);
};
};
if(doc.addEventListener){
window.addEventListener("load",init,false);
}else{
window.attachEvent("onload",init);
}
}
//跟踪用户的clickstream,每点击一次,想服务端发一个请求进行记录
this.monitor = function(){
if(!modid) return;
var doc = window.document,
node = doc.documentElement,
url = 'http://www.atpanel.com/mjzx.2.',
logImage; //据说直接new Image().src = '' 因为垃圾回收会发生请求中断的情况,所以这里用一个变量来引用它
function getUrl(id){
return url + modid + '?t=' + new Date().getTime();
}
function handleClick(e){
try{
e = e || window.event;
var elm = e.target || e.srcElement,
i = 0,
isLink,//判断冒泡过程中,元素本身或者元素祖元素是不是A元素
max = 3;
do{
if(elm.nodeType === 1){
if(!isLink && i++ > max){//这里首先冒泡3层,如果此时元素仍不是a,则取消冒泡
return;
}
if(elm.nodeName.toUpperCase() === 'A'){
isLink = true;
logImage = new Image();
logImage.src = getUrl(elm.id);
return;
}
}
}while((elm = elm.parentNode) && (elm !== doc.body))
}catch(e){}
}
if(node.addEventListener){
node.addEventListener('click', handleClick, false);
}else if(node.attachEvent){
node.attachEvent('onclick', handleClick);
}
}
};
Loader.init();
Loader.monitor();
window.onload = function(){
var element = document.getElementsByTagName('body')[0];
window.name = element.innerHTML;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment