Ways to detect if a script-blocking ad blocker like Ghostery is preventing a file from loading

I am currently working on a method to detect if ghostery is preventing google doubleclick ad scripts from being loaded. I prefer not to use a listener and instead want a straightforward way to determine if the script or URL is being blocked. Although the code I have devised consistently leads to errors, I am able to distinguish between the different error messages. I am hopeful for a more effective solution than relying on a faulty ajax call.

My objective is simply to track the number of users who are not seeing ads due to having an ad script blocker enabled.

  $.ajax({
    url: 'http://www.googletagservices.com/tag/js/gpt.js',
    type: 'GET',
    error: function(d) {
      console.log('error', d, '/error');
      if(d.statusText != 'error') {
        console.log('ghostery enabled');
      } else {
        console.log('script is not blocked');
      }
    }
  });

Answer №1

It appears that this particular approach is currently the only available option without utilizing intervals or timeouts.

<script src="http://www.googletagservices.com/tag/js/gpt.js" onload="callback()" onerror="error()"></script>

function callback() {
  // It is important to check that the gpt object is not empty, especially for certain ad blockers in Chrome
}

function error() {
  // Most ad blockers that block scripts will trigger this function. In my experience, ad blockers like Ghostery and Disconnect in Firefox lead to this error.
}

Answer №2

Experience a timeout with a function test to verify whether the global variable established by the script has been initialized. For example;

function checkExternalScript(src, test, callback) {
  var s = document.createElement('script');
  s.src = src;
  document.body.appendChild(s);

  var callbackTimer = setInterval(function() {
    var call = false;
    try {
      call = test.call();
    } catch (e) {}

    if (call) {
      clearInterval(callbackTimer);
      callback.call();
    }
  }, 100);
}

Implement it like this:

this.checkExternalScript('www.domain.com/script.js', function () {
    return (typeof window.myscriptobject === 'undefined');
}, onScriptFailedToLoad);

You will be loading the script externally using JavaScript, and then check if its global variable has been set. If it hasn't been set by the end of the timeout, you can assume that it failed to load. Keep in mind that although this method is not flawless, using a longer timeout would offer more security, although still not perfect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the content of a file and convert it into JSON or GeoJSON format

Can someone help me with my issue? I am struggling to extract content from geojson files and assign it to a valid variable. Here is what I've tested: //this works var obj_valid = {"type": "FeatureCollection","crs": { "type": "name", "properties": { ...

ObjectID is failing to store the hexadecimal values properly

Initially, the ObjectID in my Sails/Mongo database was stored like this: "_id" : ObjectId("557077fb836bdee256004232") However, something changed or happened, and now new records are stored differently: "_id" : { "_bsontype" : "ObjectID", "id" : ...

In React, when a user clicks the back button on the browser window, ensure you pass props back to the originating component

While moving from component A to component B through routing, I want to send a prop back to A when the user clicks on the browser's back button while on B. Can this be achieved? I am currently using React's history.push for navigating between com ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

A guide to incorporating nested loops with the map method in React JS

I've come across numerous threads addressing the nested loop using map in React JS issue, but I'm still struggling to implement it in my code. Despite multiple attempts, I keep encountering errors. Here are some topics I've explored but cou ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Firefox with Ajax bug bar

I have encountered an issue with my Navbar specifically on Firefox. The problem I am facing is that the Navbar is flickering, constantly growing and shrinking. Interestingly, this issue does not appear when using Chrome or Opera. I'm curious to know ...

Aurelia-powered DataTable plugin for effortless data updating

I'm currently utilizing the DataTables and DatePicker plugins along with Aurelia in my project. The goal is for the user to select a date, which will then prompt the data table to display the corresponding data for that specific date. However, I' ...

The mongoose library is not throwing any errors, indicating that the database connection has been established successfully

There are no errors in my code and it's a simple mongoose query - const posts = await Post.find(); console.log(posts); res.status(200).json({ status: 'success', results: posts.length, data: { ...

Using React to easily rearrange images by dragging and dropping them

Currently, I am working on incorporating drag-and-drop functionality using React JS along with the react-dropzone library to display thumbnails. The code implementation is provided below: import React from "react"; import ReactDOM from "react-dom"; impor ...

Issues with location forecasts and .getPlace() when utilizing the Google Maps loader for Place Autocomplete in Vue are causing functionality problems

After setting up a Vue 2 app using the vue cli, I noticed that when typing an address, no suggestions were populating from the dropdown. Checking the network tab, I observed the AutocompletionService.GetPredictions call triggering without any errors upon p ...

The build process encountered an error due to the absence of ESLint configuration after the import

Having recently worked on a Vue project created using Vue CLI, I found that eslint was also included in the project. Although I haven't utilized eslint much up to this point, I understand that it is beneficial for catching stylistic errors, semantic e ...

Getting started with jquery plugins: installation and usage

I have some questions as a beginner. Firstly, I'm interested in obtaining this plugin: Unfortunately, I am having difficulty downloading it and seem to be stuck in a loop. Can someone guide me on the exact steps to download it? Secondly, how do I go ...

Is it possible to execute multiple database queries simultaneously within a single PHP session?

I have encountered some challenges while handling multiple database calls, especially when dealing with large datasets. It seems that PHP restricts the execution of only one database call at a time per session. This limitation is typically not problematic ...

Update the FontSize in the HTML dropdown menu using JavaScript

I am having trouble filling my Selection using a script. For example, when I try to populate my FontSizeMenu, I use the following code snippet: function FillFontSizeMenu() { FillSelection(GetPossibleFontSizes(), "fontSizeMenu"); } function GetPossib ...

Combining button id with bound values in jQuery

This is a custom div tag. <div id="generate"> </div> The dynamic HTML I created includes an input type button control that is bound with a unique message ID for easy differentiation while clicking. <input type="button" onclick="return ...

Understanding the significance of the argument in the context of `express.json({ extended: false})`

Currently, I am in the process of setting up an API using express and encountered this particular line of code: app.use(express.json( { extended: false } )); Although I have referred to the documentation provided by express, I was unable to locate this sp ...

`Learning how to implement Jquery AJAX within Joomla Components`

While I am in the process of developing a site in Joomla, I have encountered a problem that has me stuck. I would greatly appreciate any assistance with the following issue: Below is the folder structure for my component: htdocs/Joomla/administrator/comp ...

Creating dynamic django modal popup forms with AJAX integration for server-side data processing

Looking for innovative solutions and modern patterns or Django apps to efficiently handle server-side forms that appear in a popup window. Here's what I'm after: User triggers a modal popup window through an action. The form ...