Note
Production-Ready Client-Side Ad Shield: Protect your web application and its visitors from rogue iframe ads, malicious popunders, and clickjacking without requiring users to install third-party browser extensions.
Developed by JOJIN JOHN
It intercepts DOM iframe creations before they execute, evaluates domains against threat heuristics, and neutralizes rogue ads and popups on the fly. No ads, zero breaking changes.
This repository is iframe-shield: the lightweight (< 4KB) open-source developer SDK.
Add to your website
<script src="https://cdn.jsdelivr.net/npm/@jojin1709/iframe-shield/dist/iframe-shield.min.js"></script>Drop-in CDN script tag auto-initializes with zero configuration required.
Quick Start • Swagger API Docs • Key Capabilities • Architecture • Configuration • Playground • FAQ
Tip
Using a modern bundler? Install via npm: npm install @jojin1709/iframe-shield and import { IframeShield } from '@jojin1709/iframe-shield'. Full TypeScript and modern ESM/CommonJS modules are supported out of the box.
- Table of Contents
- What is iframe-shield?
- Quick Start
- Key Capabilities
- Architecture
- Configuration
- Interactive Playground
- Testing and Verification
- Common Questions
- Author & Credits
- License
iframe-shield is a developer-facing JavaScript security library that runs directly inside your web application to intercept, sandbox, or eliminate intrusive iframe advertisements, unwanted affiliate redirects, and tracking frames.
Whether you run a video platform, content portal, blog, or embed third-party widgets and user-generated content, iframe-shield ensures third-party scripts cannot inject rogue popups, redirect your users, or litter your layout with unvetted ads.
Why iframe-shield Exists
Many web applications rely on third-party widgets, syndication feeds, video players, or user-generated HTML. Often, these third-party scripts inject rogue iframes that deliver spam advertisements, open intrusive background tabs (popunders), or redirect users to scam landing pages.
Browser ad-blocker extensions only protect the individual user who has them installed. iframe-shield shifts protection directly into the site itself: every single visitor gets clean, ad-free, and safe browsing without needing any browser extensions.
How It Differs from Browser Extensions
Traditional ad blockers require users to download an extension from the Chrome Web Store or Firefox Add-ons. If a mobile user, safari user, or regular visitor doesn't have an ad blocker installed, they are exposed to intrusive ads and redirection attacks.
iframe-shield is integrated directly by the web developer into the application code. It runs automatically in every browser—desktop, mobile, iOS Safari, Android Chrome, and embedded WebViews.
Preserves Legitimate Third-Party Embeds
Naive ad blockers often break essential site features like payment forms, captcha verifications, and legitimate media players.
iframe-shield ships with a pre-calibrated whitelist of trusted services—including YouTube, Vimeo, Stripe Checkout, PayPal, Google reCAPTCHA, and Cloudflare Turnstile—so your critical business infrastructure and user media continue to work without a hitch.
Add this script tag to your HTML <head> or before the closing </body> tag:
<!-- Load and auto-initialize iframe-shield -->
<script src="https://cdn.jsdelivr.net/npm/@jojin1709/iframe-shield/dist/iframe-shield.min.js"></script>Note: When loaded via
<script>,iframe-shieldinitializes automatically with secure defaults. To configure it manually, declarewindow.__IFRAME_SHIELD_NO_AUTO__ = true;before loading the script.
npm install @jojin1709/iframe-shieldimport { IframeShield } from '@jojin1709/iframe-shield';
// Initialize with custom options
IframeShield.init({
action: 'sandbox', // 'sandbox' | 'remove' | 'blank'
sandboxUntrusted: true,
onBlocked: (event, iframe) => {
console.warn(`[Shield] Intercepted ad from ${event.src}:`, event.reason);
}
});Deploy the ready-to-use worker located in integrations/cloudflare-worker.js directly to Cloudflare:
// Automatically injects iframe-shield at the edge & enforces anti-clickjacking CSP headers
export default {
async fetch(request) {
const response = await fetch(request);
return new HTMLRewriter().on('head', {
element(el) {
el.append('<script src="https://cdn.jsdelivr.net/npm/@jojin1709/iframe-shield/dist/iframe-shield.min.js"></script>', { html: true });
}
}).transform(response);
}
};- Pre-emptive Interception: Wraps
document.createElement('iframe')andNode.prototype.appendChildto neutralize malicious iframes before the browser issues network requests. - Dynamic Mutation Monitoring: Uses an active
MutationObserverto immediately process iframes injected viainnerHTML, template literals, or dynamic Single Page App routing. - Calibrated Whitelist: Pre-configured to automatically pass trusted providers (YouTube, Vimeo, Twitch, Stripe, PayPal, reCAPTCHA, Cloudflare, Google Maps, Spotify, etc.).
- Built-in Ad Network Blacklist: Targets known ad syndication domains (DoubleClick, PopAds, Adsterra, PropellerAds, Taboola, Outbrain, Criteo, RevContent, Exoclick, etc.).
- Tracking Pixel Neutralization: Detects and suppresses hidden 1x1 and 0x0 tracking iframes.
- Safe Sandboxing (Default): Restricts untrusted frames with
sandbox="allow-scripts allow-same-origin", strippingallow-top-navigationandallow-popupsto eliminate redirect hijacks and spam tabs. - Comprehensive Observability: Offers a real-time event hook (
onBlocked) and telemetry counters (getStats()). - Zero Dependencies: Pure, lightweight vanilla JavaScript (< 4 KB gzipped).
flowchart TD
CREATE["document.createElement('iframe')<br/>or DOM Mutation"] --> INTERCEPT["iframe-shield Interceptor Engine"]
INTERCEPT --> CLASSIFY{"Domain & URL Classifier"}
CLASSIFY -- "Trusted Whitelist<br/>(YouTube, Stripe, Maps)" --> PASS["Allow Execution<br/>(Preserve Embed)"]
CLASSIFY -- "Known Ad Network /<br/>Ad Pattern / 1x1 Pixel" --> BLOCK{"Configured Action"}
CLASSIFY -- "Untrusted 3rd-Party" --> SANDBOX_UNTRUSTED["Apply Safe Sandbox<br/>(Block Popups & Navigation)"]
BLOCK -- "action: 'sandbox'" --> APPLY_SANDBOX["Apply sandbox flags<br/>(Disarm redirects & popups)"]
BLOCK -- "action: 'remove'" --> DETACH["Remove node from DOM"]
BLOCK -- "action: 'blank'" --> BLANK["Replace src with about:blank"]
APPLY_SANDBOX --> TELEMETRY["Update Stats & Fire onBlocked()"]
DETACH --> TELEMETRY
BLANK --> TELEMETRY
Pass these options to IframeShield.init(options):
| Option | Type | Default | Description |
|---|---|---|---|
action |
'sandbox' | 'remove' | 'blank' |
'sandbox' |
Action to execute on detected ad iframes. |
sandboxFlags |
string |
'allow-scripts allow-same-origin' |
Attributes assigned when sandboxing an ad or untrusted iframe. |
sandboxUntrusted |
boolean |
true |
Apply safe sandbox attributes to any third-party iframe not in the whitelist. |
blockTrackingPixels |
boolean |
true |
Neutralize 1x1 and 0x0 hidden tracking iframes. |
blockClickjackingOverlays |
boolean |
true |
Detect transparent overlay iframes (opacity near 0 with high z-index). |
matchDimensions |
boolean |
false |
Flag iframes matching standard IAB ad banner sizes (e.g. 300x250, 728x90). |
trustedDomains |
string[] |
[] |
Additional custom domains to always allow. |
adDomains |
string[] |
[] |
Additional custom ad domains to block. |
adPatterns |
RegExp[] |
[] |
Additional regular expressions to match against iframe URLs. |
onBlocked |
function |
null |
Callback function fired on every blocked ad event: (event, iframe) => void. |
debug |
boolean |
false |
Output detailed inspection logs to browser console. |
import { IframeShield } from 'iframe-shield';
// Initialize the shield
IframeShield.init(options);
// Retrieve live metrics
const stats = IframeShield.getStats();
console.log(stats.scanned, stats.blocked, stats.sandboxed, stats.history);
// Dynamically whitelist a trusted partner domain
IframeShield.allowDomain('custom-partner-embed.com');
// Dynamically block a new ad network
IframeShield.blockDomain('malicious-ad-domain.net');
// Listen to block events
IframeShield.onBlocked((event, iframe) => {
console.log(`Blocked: ${event.src} | Reason: ${event.reason}`);
});
// Clean up and restore original DOM methods
IframeShield.destroy();A complete interactive testing dashboard is hosted live on GitHub Pages:
Alternatively, preview locally:
- Open
demo/index.htmldirectly in your browser. - Click injection buttons to simulate real-time ad network attacks (DoubleClick, PopAds, Tracking Pixels) vs. trusted embeds (YouTube, Stripe).
- Observe live counter updates and the real-time event log feed.
Run the automated test suite to verify classification, sandboxing, and whitelisting:
npm testBuild the distribution bundles (.min.js, .esm.js, .cjs.js):
npm run buildNo. iframe-shield maintains a built-in whitelist for established platforms (YouTube, Vimeo, Stripe, PayPal, Google reCAPTCHA, Cloudflare Turnstile, Spotify, etc.). You can also add custom domains via trustedDomains: ['example.com'] or IframeShield.allowDomain('example.com').
When an iframe is sandboxed with allow-scripts allow-same-origin, the browser permits the internal content to display and function, but strictly blocks:
- Top-frame redirects (
allow-top-navigationis omitted) - Unsolicited popups and new tabs (
allow-popupsis omitted) - Modal dialogs and automatic downloads (
allow-modalsandallow-downloadsare omitted)
This disarms video player overlay ads and redirects without breaking the video player itself.
Yes. Use IframeShield.allowDomain('domain.com') to permit new trusted embeds or IframeShield.blockDomain('bad-domain.com') to block newly identified ad hosts on the fly.
Yes. Because iframe-shield uses both monkey-patching of element creation methods and an active MutationObserver, any dynamically mounted component or client-side route change is protected automatically.
Developed by JOJIN JOHN
Contributions, bug reports, and suggestions are welcome!
Distributed under the MIT License.