I'm doing the frontend on my clients website and have come across a strange issue. On certain pages (maybe 5% of the total pages on the site), the simple hamburger icon javascript doesn't function at all.
Here is the JS (which, again, works on 95% of the pages):
const userBox = document.querySelector(".wdgt-user-box");
const userBtn = document.querySelector(".wdgt-login");
function toggleUserBox() {
if (userBox.style.display === "block") {
userBox.style.display = "none";
}
else {
userBox.style.display = "block";
}
}
userBtn.addEventListener("click", toggleUserBox);
Some things to rule out:
Z-index is not an issue. I can click on the icon (I tried adding an href and it worked).
The HTML and JS (and how the JS is linked) is exactly the same on all pages. The JS is included at the bottom of the HTML in all cases
The queryselector appears to be working in all cases when inspecting with Chrome dev tools
The one difference I noticed when setting up breakpoints is that when hovering over "toggleUserBox" on the pages where it doesn't work, Arguments: null. Here is the difference between the two:
Of course, please let me know if there is more useful info I can find. I'm new to Chrome dev tools.
Since you are using a class as the query selector, you could try checking if there is more than one object with the same class name on the page
According to this article, display-mode: standalone only can detect on M48 or newer version. Is there any way to detect the mode on older version?
No this is not possible.
Check this article
#supports for display-mode is only supported starting with Chrome 48.
Although it's not a direct answer but it's offering a workaround.
As much as I understand the article, you can configure your website (in the manifest.json) to open with querystring (for example) if it opens from the homescreen. So you can set a flag on the DOM - let's say add class to the body tag. In this way you can detect in eitgher css or js if you run in standalone mode.
For example:
var isStandalone = false;
if (location.search.indexOf('standalone=true') > -1) {
isStandalone = true;
document.body.classList.add('standalone-mode');
}
// from now on you can check if you run in standalone by checking 'isStandalone' param.
header {
background: red;
}
/* this is a style for standalone mode only */
body.standalone header {
background: green
}
For applications wrapped in electron you might use what is described here: https://github.com/electron/electron/issues/2288
window && window.process && window.process.type
or
navigator.userAgent.toLowerCase().indexOf(' electron/') > -1;
I'm new here. And very new to programming, markup, web dev. I do have some basic understanding of HTML and CSS, but this is my first attempt at using jQuery/Javascript.
Is it possible to use jQuery (or otherwise) to
1- detect if an iframe with class="iframe1" appears on a given page and
2- if it does exist, to remove the primary navigation bar with id="main-header" ?
I'm currently using this custom CSS to hide the navigation globally:
#main-header {
display:none !important;
}
and then using this (for example) to replace it on individual pages:
.page-id-1350 #main-header {
display:block !important;
}
Obviously this is not ideal, and I very much like to automate this process.
Thanks very much in advance,
Chris
You can use the following jQuery code to do just that:
if($(".iframe1").length > 0) // If .iframe1 exists
$("#main-header").hide(); // Hide #main-header
Or, go the opposite way, keep your CSS that hides #main-header and then show it when .frame1 is not present on the page:
if($(".iframe1").length == 0) // If .iframe1 does not exists
$("#main-header").show(); // Show #main-header
You could do this with JavaScript, with code like this:
<script>
// Place this at the end of the body
window.addEventListener("load", function(){
var iframeTest = document.querySelectorAll("iframe.iframe1");
var navBar = document.getElementById("main-header");
if (iframeTest.length > 0) {
navBar.setAttribute("style","display:none");
}
});
</script>
After searching Google and Stackoverflow for a few hours I could not find a solution.
What I'm trying to do is detect Adblock plus and display a simple message for now.
What I want to do is detect Adblock plus without using a JavaScript file or jQuery.
Most of the adblock plus detect scripts they use a file, example "show_ads.js" that is hosted on there own domain with a line it in to set it "adblock = false;"
The problem with using a JavaScript file, users can white list that JavaScript file and it will no longer detect it. What I'm looking for is a JavaScript that loads directly into the HTML that would detect if someone is using ad blocker without the use of a file.
Example Below:
<script type="text/javascript">
// line of code that detects if using ad blocker
if so display message
</script>
The reason behind doing it this way no ad blocker can white list the JavaScript file on your server. Yes I know there are other methods of getting around this with NoScript addons but I already have a solution for that. I have a great idea that has never been tried and ad blockers cannot block this once I get done with it.
Any suggestions and Examples will be greatly appreciated.
You don't need to have a plugin to detect adblock, simply use this:
<script type="text/javascript">
var adblock = true;
</script>
<script type="text/javascript" src="adframe.js"></script>
<script type="text/javascript">
if(adblock) {
//adblock is installed and enabled on this site :-D
}
</script>
Content of adframe.js:
adblock = false;
Update:
Adblock Plus blocks certain requests or hides certain elements based on patterns it already has. One of those patterns is this (in patterns.ini):
[Filter]
text=/adframe.
hitCount=843
lastHit=1456391595626
which blocks any URL that has /adframe. in it.
Update 25th august 2018
Adblock plus has changed the way it finds the list and blocks the ads. It has bunch of lists called subscriptions which are used for blocking. For example this one which is the default one:
https://easylist-downloads.adblockplus.org/easylist.txt
You can use the rules on this file to find a file name to use. For example you can use seo-ads.js
P.S for developers: For some reason I couldn't get ABP to block these files on local environment.
P.S: ABP is my favorite ad blocker :-D
Use my plugin "FuckAdBlock", it can very easily detect AdBlock:
https://github.com/sitexw/FuckAdBlock
Example :
fuckAdBlock.on(true, function() {
alert('AdBlock detected !');
}).on(false, function() {
alert('AdBlock is not detected =)');
});
Example online: http://fuckadblock.sitexw.fr/
What I've seen in the field is using a background image behind the ad. If adblock isn't active, the ad will be displayed over the background-image (which makes the background-image not viewable). If adblock is active, the ad is blocked, and the user will instead see the background-image.
<div id="ad-container">
<img src="../ad/ad.png" id="ad">
</div>
With CSS:
#ad-container {
background-image: url( http://domain.com/pleasedonotuseadblocker.png );
height: 200px;
width: 200px;
}
#ad {
height: 200px;
width: 200px;
}
If you want to ads to be showing, even when AdBlock is active, you'll have to understand what AdBlock is capable to do.
AdBlock can block resources from loading
AdBlock can hide specific elements in the DOM.
Although it is said that AdBlock can also modify CSS, I can't find any documentation on that other than hiding and collapsing elements.
So what exactly could you do to be 'smarter' than AdBlock?
You could disguise your request in a way that it will never be 'matchable' (e.g. http://domain.com/ae9a70e0a.png, where the image name will be random every time and without a common prefix). As far as I am aware, a rule in AdBlock cannot contain a regex. A rule would either match no ads, or too many resources. It would be possible to rewrite such an url on the server to point to your ad.
However, while AdBlock might not be able to block your ad from loading, it might still be able to hide it. There is no real way of going around this. There will always be a smart CSS selector that will -just- select your element. You could however add a background-image with content. This is not useful for an ad (not clickable), but might help you display an other message. Downside is that if someone decides to block that annoying background image, it will hide your content too.
As far as a script goes, you might be able to load the ad with an ajax request. I suppose (but cannot test) that it will give an error if the resource could not be loaded (because it was blocked). ($.ajax( request ).error( function() { ... } ); in jQuery or some equivalent in regular javascript). You could use that to do something else. You could include that in the document itself, instead of an external resource, to ensure it will always run (if javascript is enabled). Even then, you cannot be sure that 'whatever else you do' will ever be visibly displayed. As last resort you can make a window.alert( ... ). Assume that within 3 pages, your visitors will never come back if you use that.
An other way I can think of, is making a websocket to the server (afaik this cannot be blocked by AdBlock). On the server side you'll need to examine if the ad pages are not loaded when a certain page is loaded. This information can be sent through the socket, which can be used in your script to do 'something'. This, however, sounds crazy complicated and is a significant overhead for 'just' a script that detects AdBlock.
A simple Ajax call does the job:
var xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange = function() {
if( xmlhttp.readyState == XMLHttpRequest.DONE ){
if( xmlhttp.status !== 404 ){
console.log("Blocking ads")
}else{
console.log("Not blocking ads")
}
}
}
xmlhttp.open("GET", "/498100ffe815d700cd838d1/ads/showad.js", true)
xmlhttp.send()
Or even better, without the HTTP overhead:
var adBlockTester = document.createElement('div');
adBlockTester.innerHTML = ' ';
adBlockTester.className = 'adsbox';
document.body.appendChild(adBlockTester);
window.setTimeout(function() {
if( adBlockTester.offsetHeight === 0 ){
console.log("Blocking ads")
}else{
console.log("Not blocking ads")
}
document.body.removeChild(adBlockTester);
}, 60);
The following snippet will pretty much detect all ad blockers. Requires jQuery.
(function(){
var bait = 'http://googleads.g.doubleclick.net/pagead/gen_204?id=wfocus&gqid=advertisment&advert=ads';
$.ajax({ url: bait, dataType: "script"})
.fail(function () { alert('ad blocked'); })
.abort(function () { alert('ad blocked'); });
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It's wrapped in a self-executing anonymous function so it doesn't interfere with other vars or code on the site.
The bait uses the most popular ad serving network (Google's double click) and includes a few other query params used by easylist and others.
The fail() and abort() methods are both required, but only one or the other will be invoked.
Don't put the code in adblocker.js or similar since those sort of filenames themselves get blocked from loading. Either inline it or include it in an random/arbitrary filename or combine it in your main site JS file.
Here is the code to detect adblock. You can learn how the code works here
function detect()
{
//create a iframe. Append the iframe to the body. And then after 100ms check if their offsetHeight, display or visibility is set such a way that user cannot see them.
//In the URL use the words specific to advertising so that Adblock can do string matching.
var iframe = document.createElement("iframe");
iframe.height = "1px";
iframe.width = "1px";
iframe.id = "ads-text-iframe";
iframe.src = "http://domain.com/ads.html";
document.body.appendChild(iframe);
setTimeout(function()
{
var iframe = document.getElementById("ads-text-iframe");
if(iframe.style.display == "none" || iframe.style.display == "hidden" || iframe.style.visibility == "hidden" || iframe.offsetHeight == 0)
{
alert("Adblock is blocking ads on this page");
iframe.remove();
}
else
{
alert("Adblock is not detecting ads on this page");
iframe.remove();
}
}, 100);
}
Simple javascript/jQuery detection that works nicely:
$('body').append('<div id="ad-container" style="position:absolute;"><img src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" id="ad"></div>');
var ad_container = $('body').children('#ad-container');
if(!ad_container.is(":visible")) {
// Add your warning and/or adblock detection logic here.
}
ad_container.remove();
The Smartest and easiest way I found is:
1) add this html code on somewhere in your markup probably on top.
<div id="bait" class="pub_300x250" style="color: #fff">.</div>
Usually ad blockers detect ad sizes of (pub_300x250) as mentioned in Easylist and blocked them, which is triggered by "bait".
2) then add this js code into your script file.
if (document.getElementById("bait").offsetHeight === 0) {
// function code or alert (whatever) here.
alert("Ad-Blocker DETECTED");
}
Our Script detects if that piece of markup is existed in present html by checking thorugh "bait" id.
This works for me with Adblock , AdBlock-Plus & uBlock Origin on every site on every browser.
For me none of the tricks worked, may something I was doing wrong. but this is a very specific way to implement for google ads.
window.onload = function() {
if (document.getElementsByClassName('google-auto-placed').length == 0){
// Adblock Detected
}
}
If you have other ad system like amazon, look for their generic class name / ids by inspecting page.
If you are planing to put this code in seperate .js file make sure file name does not have "Ad" word in it. just name it magic.js
If Google ever decides to change div name, this method would fail. but that seems unlikely.
In my case ADB was hiding the content even that there were no ads.. ( just because the ad word was present in many urls, because it was the post type slug.. )
But I noticed that they don't remove the content, just applying display: none to the body
So as an extra solution,
I just noticed that applying display: block !important; to de body, prevents hiding the content by Adblock plus
<body style="display: block !important;">
<img src="url-containg-ad-ads-word.jpg" alt="you should see this anyway" >
</body>
It's an arms race, for sure, and I support anyone's right to block ads, but I also support websites that depend on ad revenue trying to convince users otherwise, or perhaps persuade them to subscribe or make a donation to make up for lost ad revenue. I don't approve of sites trying to force users to see ads, but a polite message is fine.
Anyway, right now it's worth noting that there are many adblocking extensions/plugins, and they can all have different ways of doing it, and it sometimes is different between OSes and browsers too. I've found that for my purposes right now, this jQuery selector is enough to at least see whether AdBlock or AdBlockplus is being used, cross-platform, across at least Chrome and Firefox:
if($("div[id^=google_ads_iframe_] iframe:visible").length == 0) {
// pop up a message or whatever
}
Here is a simplest way to deal with it (no iframe, no jquery):
var elem = document.createElement('div');
elem.className = 'adclass';
document.body.appendChild(elem);
window.setTimeout(function () {
var isAdblockEnabled = !(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
if (isAdblockEnabled) {
// Adblock is enabled
}
}, 0);
I know this is kinda old, but here's IMHO a better way to do it:
Add this to your <head> section:
<script type="text/javascript">
window.onload = function() {
var iframe = document.createElement('iframe'),
randomDomain = Math.floor(Math.random() * (10000 - 100 + 1)) + 100,
iframeLoaded = true;
iframe.src = "http://"+ randomDomain +".com/ads.html";
iframe.height = ".1px";
iframe.width = ".1px";
iframe.id = 'some-ad';
iframe.onload = function() {iframeLoaded = false;};
document.body.appendChild(iframe);
setTimeout(function() {
var someAd = document.getElementById('some-ad');
if(!iframeLoaded ||
someAd == null ||
someAd.style.display == "none" ||
someAd.style.display == "hidden" ||
someAd.style.visibility == "hidden" ||
someAd.offsetHeight == 0)
document.getElementById('ab-message').style.display = 'block';
someAd.remove();
}, 500);
};
</script>`<br>
Now you can use the ab-message id wherever you want to display a message to AdBlock users:
<div id="ab-message" style="display: none">Your message here!</div>
Note the inline style added to hide it originally (Of course, you can also do this from your own CSS file).
Also note that it takes 500ms, that's because it has to wait for the adblocker to do its thing or it won't work.
A little explanation of how this script works
First, it appends an iframe with a source of a randomly generated link. (It is randomly generated because some adblocks are smart, at some point, they realize a link is fake).
Then it runs multiple checks on that iframe (if it was loaded successfully or if its style was modified). If one of these tests is true, it then displays the ab-message element to adblock users.
This script works for most (if not all) ad blockers.
EXTRA
No point, really, could have just created a gist, but instead I created a Github project, but still, check it out and star it if it helped you.abDetector: Simple vanilla JavaScript AdBlock Detector.
Enjoy.
I have found one of the best scripts if you use third party ads.
antiblock.org Disclaimer I'm not affiliated with this site in anyway.
It will work for most sites and if they want to bypass it they will have to add their own filters (complicated for normal users) or contact adblock filters and have one added but they quit doing that cause the list is getting over loaded and slowing down ad block users.
I'm experimenting with a Chrome extension that will remove the ads displayed in the right-hand pane in Gmail and instead put the information I want there. (I haven't decided exactly what to put there yet; vacillating between several ideas, including external content and/or attachments.)
The ads are (usually) contained in a <div class="oM"></div> element. But I can't seem to select that either in my extension or in the console.
I've tested my manifest.json settings by writing an extension that added a superfluous div to the top of the page, and that worked fine -- I just created a new element and
document.body.parentElement.insertBefore(new_el, document.body);
However, what I'm trying to do now is just rip out the ads and put in some dummy text, or just put the text above the ads. This is the main function called in my content_script.js file.
function modifyPage(txt) {
var container = document.getElementsByClassName('oM')[0];
container.innerHTML = txt;
}
function modifyPage(txt) {
var insert = document.createElement('div');
insert.innerText = txt;
var container = document.getElementsByClassName('oM')[0];
document.body.parentElement.insertBefore(insert, container);
}
I've even tried to jQuery:
function modifyPage(txt) {
$('.oM').html(txt);
}
Also, trying to retrieve the <div class="oM"> using the Chrome console returns nothing -- even though I can see it right there in the source.
Set a delay on the execution of your jquery selector. The Google Tubes are a bit more complicated than using static div classes on page load.
Rather than remove the ads with JS, just hide them with CSS:
.oM {
display: none;
}
I'm using AdBlock + Chrome add-in(or extension).
It works very well it's a donation-ware, I'm guessing the author use jquery {display:none } to hide or remove the ads with a custom filter lists.