Reputation: 301
I am developing a ads blocker script and I have placed a div with classes like this =
<div id="detect" class="ad ads adsbox ad-placement doubleclick ad-placeholder ad-badge"></div>
If ads blocker is present on the browser then it will make the css attributes display none by the browser.
So here I want to check if this class is displayed or not on the browser. If the class is displayed then I want to show text that says ads blocker not available and if the div element is hidden with none properties with ads blocker extension does then we will display ads blocker is present text.
How can I detect the property of display: none !important; this attribute with javascript?
Upvotes: 0
Views: 89
Reputation: 74
You can try something like this:
window.addEventListener('DOMContentLoaded', (event) => {
let ads = document.querySelectorAll('.ad, .ads, .adsbox, .ad-placement, .doubleclick, .ad-placeholder, .ad-badge');
for(let i in ads){
if(ads[i].style.display === 'none') document.getElementById('presence').innerHTML = 'Adblock Present'
}
});
<div id="detect" class="ad ads adsbox ad-placement doubleclick ad-placeholder ad-badge">Hello</div>
<div id="detect" style="display: none !important;" class="ad ads adsbox ad-placement doubleclick ad-placeholder ad-badge">This is a hidden ad</div>
<b id='presence'></b>
However, i recommend you to also check this answer so you can refine the method of getting styles from elements. ie getComputedStyle
Upvotes: 1
Reputation: 7179
It sounds like you're looking for the Window.getComputedStyle()
method which:
[...] returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
In this case, you're looking for the value of the display
property. You may have to wait for the document's load
event depending on how your adblocker works.
If you need to check that the !important
flag is used, you can additionally call the CSSStyleDeclaration.getPropertyPriority()
method. The following sample shows both:
const canary = document.querySelector('div#detect');
const style = getComputedStyle(canary);
if (style.display === 'none') {
console.log('Adblocker active.');
const isImportant = style.getPropertyPriority('display') === 'important';
console.log(`Important: ${isImportant}`);
}
<div id="detect" class="ad ads adsbox ad-placement doubleclick ad-placeholder ad-badge"></div>
Upvotes: 1