iframe-shield Specification
SDK v1.0.1 • Production Spec
Official interactive developer specification and SDK reference for iframe-shield. A lightweight client-side security engine that intercepts iframe creation, neutralizes rogue ads and tracking pixels, disarms unauthorized popups and redirects, and validates trusted third-party embeds.
Installation
GETTING STARTEDInstall the package via npm, pnpm, yarn, or directly load the pre-bundled minified script via CDN.
npm install @jojin1709/iframe-shield
<!-- Load in <head> before any ad networks or untrusted third-party scripts -->
<script src="https://cdn.jsdelivr.net/npm/@jojin1709/iframe-shield/dist/iframe-shield.min.js"></script>
<script>
IframeShield.init({
action: 'sandbox',
sandboxUntrusted: true
});
</script>
Quick Start
INTEGRATIONInitialize the shield at the earliest entry point in your client-side application lifecycle. The engine immediately overrides DOM creation methods and registers a MutationObserver on document.documentElement.
import { IframeShield } from '@jojin1709/iframe-shield';
// Start DOM protection
IframeShield.init({
action: 'sandbox',
sandboxUntrusted: true,
blockTrackingPixels: true,
blockClickjackingOverlays: true,
trustedDomains: ['youtube.com', 'js.stripe.com', 'customer-portal.io'],
onBlocked: (event, iframe) => {
console.warn('[Threat Blocked]', event.src, event.reason);
}
});
DOM Boundary Interception
SECURITY ARCHITECTURE
Standard ad blockers rely on browser extension privileges or declarative network request filters. iframe-shield operates directly within the web page context using a dual-layer interception architecture:
1. API Monkey-patching: Wraps document.createElement('iframe') and intercepts the creation of the HTMLIFrameElement before it is connected to the DOM or assigned an initial src.
2. MutationObserver Fallback: Continuously monitors subtree additions across document.documentElement. Any iframe injected via innerHTML, outerHTML, or dynamic script injection is intercepted and evaluated prior to first rendering.
Threat Heuristics
DETECTION PIPELINEThe classification engine evaluates each frame against four deterministic rules in sequence:
Known Ad Network Blacklist: Matches the frame URL against over 40 known rogue ad brokers and popunder domains (e.g. DoubleClick, PopAds, Outbrain, Taboola).
Surveillance Tracking Pixels: Detects frames with width ≤ 1px and height ≤ 1px, or frames styled with display: none / visibility: hidden.
Clickjacking Overlays: Intercepts full-viewport frames with opacity ≤ 0.05 or high z-index overlays positioned directly over interactive content.
Untrusted 3rd-Party Hosts: When sandboxUntrusted: true is active, any domain not matching the built-in trusted list or configured trustedDomains is restricted with a safe sandbox policy.
Sandboxing Policy
BROWSER ISOLATION
When an iframe is classified for mitigation, the engine enforces sandbox="allow-scripts allow-same-origin" by default. Crucially, the following dangerous capabilities are omitted:
allow-top-navigation — Blocked. Untrusted iframes cannot redirect your parent application.
allow-popups — Blocked. Scripts inside the frame cannot spawn rogue popups, tabs, or new windows.
allow-modals — Blocked. Untrusted iframes cannot display alert, confirm, or prompt dialogs.
Core Engine API Reference
SWAGGER SPECIFICATIONExplore the live SDK methods below. Click on any method header to expand details, view parameters and return types, and execute live tests against the embedded browser engine.
document.createElement and begins observing dynamic node insertions across the document.
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| options.action | 'sandbox' | 'remove' | 'blank' | Optional (default: 'sandbox') | Mitigation action applied to hostile or untrusted iframes. |
| options.sandboxUntrusted | boolean | Optional (default: true) | When true, sandboxes any external frame not present in the trusted whitelist. |
| options.blockTrackingPixels | boolean | Optional (default: true) | Neutralizes hidden 1×1 or 0×0 surveillance tracking frames. |
| options.blockClickjackingOverlays | boolean | Optional (default: true) | Identifies and neutralizes full-screen invisible clickjacking overlays. |
| options.trustedDomains | string[] | Optional | Custom domain array to permit without sandboxing (e.g. ['partner.com']). |
document.querySelectorAll('iframe') and evaluates any frames rendered prior to shield initialization or via unmonitored injection.
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| domain | string | Required | Target domain string to permit (e.g. 'customer-portal.com'). |
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| domain | string | Required | Target domain string to block (e.g. 'malicious-tracking.com'). |
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| callback | (event: BlockEvent, iframe: Element) => void | Required | Callback receiving threat event telemetry and the associated DOM element. |
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| customDomains | string[] | Optional | Array of partner domains to permit in the frame-src directive. |
document.createElement.
HTML / CDN Integration
INTEGRATIONSFor static websites and traditional multi-page applications, include the UMD bundle in your HTML <head> before any third-party tags are injected.
<head>
<script src="https://cdn.jsdelivr.net/npm/@jojin1709/iframe-shield/dist/iframe-shield.min.js"></script>
<script>
IframeShield.init({
action: 'sandbox',
sandboxUntrusted: true,
trustedDomains: ['js.stripe.com']
});
</script>
</head>
npm & Modern Bundlers (Vite, Rollup, Webpack)
INTEGRATIONSImport and initialize the shield at the top of your application entry point before mounting your UI framework.
import { IframeShield } from '@jojin1709/iframe-shield';
IframeShield.init({
action: 'sandbox',
sandboxUntrusted: true,
blockTrackingPixels: true,
blockClickjackingOverlays: true
});
Next.js & React Applications
INTEGRATIONSIn Next.js (App Router or Pages Router), mount the shield in a root layout client component or standard useEffect lifecycle hook.
'use client';
import { useEffect } from 'react';
import { IframeShield } from '@jojin1709/iframe-shield';
export function SecurityProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
IframeShield.init({
action: 'sandbox',
sandboxUntrusted: true
});
return () => {
IframeShield.destroy();
};
}, []);
return <>{children}</>;
}
Cloudflare Edge Worker Integration
INTEGRATIONS
Combine client-side interception with edge-level Content Security Policies generated by IframeShield.generateCSP().
export default {
async fetch(request, env) {
const response = await fetch(request);
const newHeaders = new Headers(response.headers);
// Enforce CSP frame restrictions at the network edge
newHeaders.set(
'Content-Security-Policy',
"frame-ancestors 'self'; frame-src 'self' https://*.youtube.com https://*.stripe.com;"
);
return new Response(response.body, {
status: response.status,
headers: newHeaders
});
}
};
Data Models & Schemas
TYPESCRIPT TYPESClick each schema card to view full TypeScript interfaces and configuration structures.
Security FAQ
REFERENCE
Does iframe-shield break legitimate payment gateways or video players?
No. Legitimate providers (YouTube, Vimeo, Stripe, PayPal, Google reCAPTCHA) are pre-whitelisted by default, and custom partners can be passed to trustedDomains or added via IframeShield.allowDomain().
What is the browser performance impact?
Less than 1ms overhead per iframe creation. The MutationObserver uses native browser filtering and only executes the classification heuristic when nodes of type IFRAME are attached.
What if an ad script injects an iframe via document.write()?
The MutationObserver detects node insertions regardless of whether they originate from document.write(), appendChild(), or innerHTML changes, evaluating the frame before scripts inside can initialize.