DEV Community

Martin Ratinaud
Martin Ratinaud

Posted on • Edited on

1

Preventing adsense from injecting min-height and height inline style

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).

Alt Text

This is because adsense is injecting

 

style="height: auto!important;min-height: 0px!important" 
Enter fullscreen mode Exit fullscreen mode

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'],
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

and

render() {
  return (
    <main ref={this.mainRef}>
      {this.props.children}
    </Main>
  );
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
  }
Enter fullscreen mode Exit fullscreen mode

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!

Retry later

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up