Tracking Blocked Scripts

If you have a reference to a script in JavaScript you think might be blocked…

const script = document.createElement("script");
script.src = ``;Code language: JavaScript (javascript)

Before you add it to the page, you can add an error handler:

script.onerror = () => {
  // Chances are decent the script was blocked.
  // Track it in some way that isn't likely to also be blocked.
};Code language: JavaScript (javascript)

Then kick it off…

document.querySelector('head')?.append(script);Code language: JavaScript (javascript)

If you’re trying to detect this from <script> tags in the HTML, you can still get a reference to it the script element, but you’d have to get that reference before it tries to execute to catch the error, so whatever, do that if you want.

If the script is blocked, you’ll probably get some message like this in the console:

GET net::BLOCKED_BY_CLIENTCode language: JavaScript (javascript)

That’ll throw that onerror and you’ll be in a position to track it or respond to it if you want.

The trick on tracking is that you’ll want to use an analytics situation that won’t also be blocked. So if you’re hoping to send an event to Google Analytics or something, well, that’s not going to work very well.

I just made this mistake while running a test on CodePen to see how many calls to our advertising platform BuySellAds were being blocked. To count the blocks, I sent an event to another service we use called Appcues, thinking that Appcues isn’t an advertising service so it wouldn’t be blocked. Well, Appcues is third-party JavaScript (we don’t proxy it as we could), and some ad blockers block it. So at first, it looked like about 10% of the BuySellAds scripts were being blocked. But after replacing how we were tracking the blocks with an internal service (just a little Redis counter), it was showing more like 28% of scripts being blocked.



I work on CodePen! I'd highly suggest you have a PRO account on CodePen, as it buys you private Pens, media uploads, realtime collaboration, and more.

Get CodePen PRO

One response to “Tracking Blocked Scripts”

  1. “Appcues is third-party JavaScript (we don’t proxy it as we could), and some ad blockers block it”

    The most popular content blocking lists are EasyList, for ads, and EasyPrivacy, for general privacy-invasive things* like Appcues.

    EasyPrivacy is notably enabled by default in uBlock Origin. People using a lesser “ad block” generally only benefit from EasyList.

    They have a broad definition of “privacy-invasive”, my own is blocked by EasyPrivacy because webmasters could otherwise theoretically infer mouse movements by looking at server logs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ⬆️