2

I'm struggling to find a solution without any progress until now . I am trying to catch if the user has an AdBlocker and if it does i want to display a message advising him to turn it off. But , until now no success .

i import my component into my main container like :

<DetectAdBlock pathname={window.location.pathname} />

and then this is my adblocker.js

import React from 'react';
import PropTypes from 'prop-types'

class DetectAdBlock extends React.Component {

    static propTypes = {
        pathname: PropTypes.string.isRequired
};

    constructor(props) {
        super(props);
        this.state = {
            adBlockDetected: false
        }
        this.detectAdBlocker = this.detectAdBlocker.bind(this);
   }
    componentDidMount() {
        this.detectAdBlocker();
    }
    componentWillUpdate(nextProps, nextState) {
        if (this.props.pathname !== nextProps.pathname) {
            this.detectAdBlocker();
        }
    }
    detectAdBlocker() {
        const head = document.getElementsByTagName('head')[0];

        const noAdBlockDetected = () => {
            this.setState({
                adBlockDetected: false
            });
        }
        const adBlockDetected = () => {
            this.setState({
                adBlockDetected: true
            });
        }
        // clean up stale bait
        const oldScript = 
            document.getElementById('adblock-detection');
        if (oldScript) {
            head.removeChild(oldScript);
        }
        // we will dynamically generate some 'bait'.
        const script = document.createElement('script');
        script.id = 'adblock-detection';
        script.type = 'text/javascript';
        script.src = '/ads.js';
        script.onload = noAdBlockDetected;
        script.onerror = adBlockDetected;
        head.appendChild(script);
    }
    noticeContentJSX() {
        return (
            <div id="adblock-notice">
                <div className="message">
                    <h3>Hey, you!</h3>
                    <p>Your adblocker is on again.</p>
                    <button 
                        onClick={this.detectAdBlocker}
                    >
                        Check for Adblocker again
                    </button>
                </div>
            </div>
        );
    }
    render() {
        return (
            <div id="adblock-wrapper">
                { this.state.adBlockDetected 
                  ? this.noticeContentJSX()
                  : null
                }
            </div>
        )
    }
}
// DetectAdBlock.propTypes = {
//     pathname: PropTypes.string.isRequired
// };

DetectAdBlock.defaultProps = {
    pathname: ''
}
export default DetectAdBlock;

The problem is that there is nothing to show either i have my AdBlock enabled .

2

I think it should be easier than that. I can't actually test this as I'm at work with adblock off but something like this should work:

class AdblockDetect extends Component {
  state = {
    usingAdblock: false,
  }

  componentDidMount() {
    this.setState({ usingAdblock: this.fakeAdBanner.offsetHeight === 0 });
  }

  render() {
    if (this.state.usingAdblock === true) {
      return this.props.children;
    }

    return (
      <div
        ref={r => (this.fakeAdBanner = r)}
        style={{ height: '1px', width: '1px', visiblity: 'none', pointerEvents: 'none' }}
        className="adBanner"
      />
    );
  }
}

class App extends Component {
  render() {
    return (
      <div className="App">
        <AdblockDetect>You are using adblock</AdblockDetect>
      </div>
    );
  }
}
  • 1
    Thanks mate . It does the job perfectly . – PandaMastr Apr 11 at 16:44
  • How can I "reset" the AdblockDetect component on unmount? Also, What does "ref={r => (this.fakeAdBanner = r)}" do? – Nic Scozzaro Apr 14 at 20:44
  • For context, I'm redirecting the user instead of returning this.props.children from the code above. Then, I let the user pause their adblocker and click a button which executes history.goBack to take them back to the page with the ads (and the adblock detector). However, even though adblock is paused, the adblockdetector is still triggered. I think this is because the height is already set to 0. I tried setting this.fakeAdBanner.style.height (and width) to 1px again on componentWillUnmount, but that didn't solve it for me. – Nic Scozzaro Apr 14 at 21:16
  • Hm this sounds strange if the component was really unmounted, are you sure it's being unmounted? – Dominic Apr 15 at 8:24
1

I suggest you use the npm package react-ad-block-detect:

Install the package:

npm i react-ad-block-detect

Then try this:

import React, { Component } from 'react';
import AdBlockDetect from 'react-ad-block-detect';

class MyComponent extends Component {
    render() {
        return (
            <AdBlockDetect>
                <p>Show this if an ad blocker has been enabled.</p>
            </AdBlockDetect>
        );
    }
}
  • Yes . I am aware of this package, but i prefer to keep my code clean without usage of too many libraries . But still does the trick for somebody . Thank mate . Cheers . – PandaMastr Apr 11 at 16:46
  • 1
    Great! No problem – josemartindev Apr 12 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.