Preventing adsense from injecting min-height and height inline style
Martin Ratinaud
Posted on February 2, 2021
On https://www.edityouraudio.com, we use Adsense to monetize our audience in order to keep our service free for all non-intensive users.
This had been a very long time since my layout was sometimes broken, with the footer not being stuck on the bottom of the page, leading to a very ugly layout like this one (with the white bar at the bottom).
This is because adsense is injecting
style="height: auto!important;min-height: 0px!important"
into your main div 😱
Solving the problem with MutationObserver
Mutation observer to the rescue !
constructor(props) {
super(props);
this.mainRef = React.createRef();
this.adSenseInjectorObserver = null;
}
componentDidMount() {
if (!this.adSenseInjectorObserver && this.mainRef) {
this.adSenseInjectorObserver = new MutationObserver((mutations, observer) => {
this.mainRef.current.style.removeProperty('min-height');
this.mainRef.current.style.removeProperty('height');
});
this.adSenseInjectorObserver.observe(this.mainRef.current, {
attributes: true,
attributeFilter: ['style'],
});
}
}
and
render() {
return (
<main ref={this.mainRef}>
{this.props.children}
</Main>
);
}
This will, on component mount, define an observer that will reset the height
and min-height
everytime it is set directly by Adsense.
Don't forget to disconnect the observer on unmount also.
componentWillUnmount() {
if (this.adSenseInjectorObserver) {
this.adSenseInjectorObserver.disconnect();
this.adSenseInjectorObserver. = null;
}
}
Hire me remotely!
My name is Martin Ratinaud and I’m a senior software engineer and remote enthusiast, contagiously happy and curious.
I create websites, like this one for staking your crypto
I create bots to aggregate data and build Remote Family with them.
I create Backoffices and internal tools for marketers and growth specialists.
I also create chrome extensions and electron apps to sort your paper with AI.
All this in NodeJs and React which I love very much.
Check my LinkedIn and get in touch!
Posted on February 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 2, 2021