Skip to content

Instantly share code, notes, and snippets.

@kosatyi
Last active January 11, 2021 14:18
Show Gist options
  • Save kosatyi/e5791d19adee8326e500c0997a0115c5 to your computer and use it in GitHub Desktop.
Save kosatyi/e5791d19adee8326e500c0997a0115c5 to your computer and use it in GitHub Desktop.
Adsense fallback
(function(callback){
var findParent = function (elem, selector) {
if( !elem ) return null;
var parent = elem.parentNode;
if (parent.matches(selector)) return parent;
return findParent(parent, selector);
}
var findQueryFrame = function(id){
var selector = '[data-google-query-id="'+id+'"]';
var frame = document.querySelector(selector);
if( frame ) return frame;
frame = [].slice.call(document.querySelectorAll('iframe')).find(function(el,item){
try{
item = el.contentWindow.document;
if(item.querySelector(selector)){
return true;
}
} catch(e){}
return item;
});
return frame;
}
function adFallback(data){
var config = {qid:false,r_nh:false};
data.key_value.forEach(function(item) {
config[item.key] = item.value;
});
if(config.r_nh !== '0'){
return false;
}
var frame = findQueryFrame(config.qid);
var slot = findParent(frame,'.adsbygoogle');
if( slot === null ) return false;
callback(slot,frame);
}
window.addEventListener('message',function(event){
var data = {msg_type: false};
try{
data = JSON.parse(event.data);
} catch(e){
}
if(data.googMsgType === 'sth' && data.msg_type === 'resize-me'){
setTimeout(function(){
adFallback(data);
});
}
});
})(function(slot,frame){
var fallback = document.createElement('ins');
fallback.className = 'banner-fallback';
fallback.style.height = [frame.clientHeight,'px'].join('');
slot.parentNode.replaceChild(fallback,slot);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment