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
this is my very first question on Stackoverflow. I am currently developing a print function in my sap ui5 app to print out certain UI controls. I've got the function from here: http://embed.plnkr.co/jjyEPa1updkjBiNZqumS/preview
However, during runtime, when I click on the print button, my app only jumps to the method once and executes it correctly (to print). But after that, I can press the printbutton as often as I want, nothing happens and I can't find out why.
what the method does: i replace the body with a temporary body, which only contains the elements to be printed and execute window.print(). afterwards i insert the original body content again. Of course I use the UI controls to grab the HTML tags.
onPrintChart: function(oEvent){
var oTarget = this.getView(),
sTargetId = oEvent.getSource().data("targetId");
if (sTargetId) {
oTarget = oTarget.byId(sTargetId);
}
if (oTarget) {
var $domTarget = oTarget.$()[0],
sTargetContent = $domTarget.innerHTML,
sOriginalContent = $(document.body)[0].innerHTML;
$(document.body)[0].innerHTML = sTargetContent;
window.print();
$(document.body)[0].innerHTML = sOriginalContent;
} else {
jQuery.sap.log.error("onPrint needs a valid target container [view|data:targetId=\"SID\"]");
}
}
I managed to do it in a different, more elegant way without using a temporary body. I used CSS to hide all irrelevant elements (display: none) and keep only the relevant element for printing.
Apparently ui5 hung up when replacing the original body temporarily with another body. I noticed that ALL buttons didn't work anymore, not only the print button.
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.
A new "google related" bar shows up at the bottom of my website. It displays links to my competitors and other things like maps, etc. It is tied in with users using the google toolbar. If anyone has any ideas on how I can disable from displaying on my web side I would sure appreciate it.
Taken from http://harrybailey.com/2011/08/hide-google-related-bar-on-your-website-with-css/
Google inserts an iframe into your html with the class .grelated-iframe
So hiding it is as simple as including the following css:
iframe.grelated-iframe {
display: none;
}
Google removed div and frame names and put everything to important so original answer no longer works on my site. We need to wait for the iframe to be created and then hide it by classname. Couldn't get .delay to work, but this does...today anyway.
$(document).ready(function() {
setTimeout(function(){
$(‘.notranslate’).hide();},1000);
});
Following javascript code tries to find the google related iframe as soon as the window finishes loading. If found, it is made hidden, else an interval of one second is initialized, which checks for the specified iframe and makes it hidden as soon as it is found on page.
$(window).load(function (){
var giframe = null;
var giframecnt = 0;
var giframetmr = -1;
giframe = $("body > iframe.notranslate")[0];
if(giframe != null)
$(giframe).css("display", "none");
else
giframetmr = setInterval(function(){
giframe = $("body > iframe.notranslate")[0];
if(giframe != null) {
clearInterval(giframetmr);
$(giframe).css("display", "none");
} else if(giframecnt >= 20)
clearInterval(giframetmr);
else
giframecnt++;
}, 1000);});
Find the parent DIV element that contains the stuff in the bar. If it has an id or name attribute, and you can control the page CSS then simply add a rule for the element, i.e. if you see something like
<div id="footer-bar-div".....
then add a CSS rule
#footer-bar-div {display:none ! important}
This will not work if the bar is inside an iframe element, but even in that case you should be able to hide it using javascript, but you will need to find the name/id of the frame, i.e.:
var badFrame = document.getElementById('badFrameId').contentWindow;
badFrame.getElementById('footer-bar-div').style.display='none';
if the frame has a name, then instead you should access it with:
var badFrame = window.frames['badFrameName']
There is also a chance that the bar is generated on-the-fly using javascript. If it is added to the end of the page you can simply add a <noscript> tag at the end of your content - this will prevent the javascript from executing. This is an old trick so it might not always work.
I am writing a Firefox add-on that adds little icons next to all the urls in a web page.
The way I am doing it right now is :
window.addEventListener("load", AddIconsToURLs, false);
In AddIconsToURLs function:
Get all elements by tag name "a"
For each "a" element, append an "img" element.
However, for some web pages, the icons take a lot of time to appear since the "onload" event takes time.
Is there any faster way to make this happen ?
Rather than waiting for all the links to load and then adding icons next to each of them, is there any way to add an icon next to a link as soon as that particular link is loaded ?
Any help is appreciated. Thanks.
What do you want to do with the images? Anything special? If it is just for the look, much easier would be to load a CSS style sheet in your addon and use the :after pseudo element:
a:after {
content: url('chrome://youraddon/skin/imagefile.png');
}
No JavaScript processing involved :)
You can load a custom CSS file with:
var sss = Components.classes["#mozilla.org/content/style-sheet-service;1"]
.getService(Components.interfaces.nsIStyleSheetService);
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("chrome://youraddon/skin/cssfile.css", null, null);
if(!sss.sheetRegistered(uri, sss.AGENT_SHEET)) {
sss.loadAndRegisterSheet(uri, sss.AGENT_SHEET);
}
See also Using the Stylesheet Service.
There is another event you can listen to:
document.addEventListener("DOMContentLoaded", AddIconsToURLs, false);