iframe-shield logo iframe-shield Developer SDK

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.

RUNTIME ENVIRONMENT Browser DOM / window.IframeShield
PACKAGE @jojin1709/iframe-shield
LICENSE MIT License

Installation

GETTING STARTED

Install the package via npm, pnpm, yarn, or directly load the pre-bundled minified script via CDN.

terminal
npm install @jojin1709/iframe-shield
index.html — CDN Script Tag
<!-- 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

INTEGRATION

Initialize 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.

main.ts
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 PIPELINE

The 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 SPECIFICATION

Explore 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.

INIT IframeShield.init(options) Initialize engine and start pre-emptive DOM interception
▼
Initializes the singleton shield instance. Installs DOM boundary hooks on document.createElement and begins observing dynamic node insertions across the document.
Parameters
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']).
Returns IframeShieldEngine Active engine instance containing configuration options and stats registry.
Interactive Method Execution
RESPONSE: 200 OK
3ms
SCAN IframeShield.scan() Manually trigger a DOM sweep of all currently mounted iframes
▼
Executes a synchronous sweep across document.querySelectorAll('iframe') and evaluates any frames rendered prior to shield initialization or via unmonitored injection.
Returns void Processes frames in-place and increments internal counters.
Interactive Method Execution
RESPONSE: 200 OK
1ms
GET IframeShield.getStats() Retrieve scan counts and security threat interception telemetry
▼
Returns the current execution counters and log of all blocked/sandboxed frames. No synthetic data — metrics are read directly from the live engine runtime.
Returns ShieldStats Object containing { scanned, blocked, sandboxed, history }.
Interactive Method Execution
RESPONSE: 200 OK
1ms
ALLOW IframeShield.allowDomain(domain) Dynamically whitelist a trusted domain at runtime
▼
Adds a host string to the active trusted whitelist. Subsequent iframes loading from this domain will not be sandboxed.
Parameters
Parameter Type Requirement Description
domain string Required Target domain string to permit (e.g. 'customer-portal.com').
Returns void Modifies the runtime whitelist in-memory.
Interactive Method Execution
RESPONSE: 200 OK
1ms
BLOCK IframeShield.blockDomain(domain) Dynamically blacklist an untrusted ad domain at runtime
▼
Adds a domain to the active blacklist. Future iframes targeting this domain will immediately be intercepted and mitigated.
Parameters
Parameter Type Requirement Description
domain string Required Target domain string to block (e.g. 'malicious-tracking.com').
Returns void Appends domain to active blacklist in-memory.
Interactive Method Execution
RESPONSE: 200 OK
1ms
HOOK IframeShield.onBlocked(callback) Register an observability callback fired on every intercepted threat
▼
Registers an event hook invoked whenever an iframe is classified as an ad network, tracking pixel, clickjacking overlay, or untrusted source.
Parameters
Parameter Type Requirement Description
callback (event: BlockEvent, iframe: Element) => void Required Callback receiving threat event telemetry and the associated DOM element.
Returns void Attaches the listener to the default engine instance.
Interactive Method Execution
RESPONSE: 200 OK
1ms
GEN IframeShield.generateCSP(customDomains) Generate HTTP Content-Security-Policy & frame-ancestors directives
▼
Generates production-grade Content-Security-Policy headers restricting frame embedding to trusted sources and protecting against clickjacking overlays.
Parameters
Parameter Type Requirement Description
customDomains string[] Optional Array of partner domains to permit in the frame-src directive.
Returns string Complete Content-Security-Policy directive string.
Interactive Method Execution
RESPONSE: 200 OK
2ms
STOP IframeShield.destroy() Disconnect observer and restore original browser DOM methods
▼
Gracefully shuts down the shield. Disconnects the MutationObserver and restores native document.createElement.
Returns void Restores the host environment cleanly.
Interactive Method Execution
RESPONSE: 200 OK
1ms

HTML / CDN Integration

INTEGRATIONS

For static websites and traditional multi-page applications, include the UMD bundle in your HTML <head> before any third-party tags are injected.

index.html
<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)

INTEGRATIONS

Import and initialize the shield at the top of your application entry point before mounting your UI framework.

src/main.ts
import { IframeShield } from '@jojin1709/iframe-shield';

IframeShield.init({
  action: 'sandbox',
  sandboxUntrusted: true,
  blockTrackingPixels: true,
  blockClickjackingOverlays: true
});

Next.js & React Applications

INTEGRATIONS

In Next.js (App Router or Pages Router), mount the shield in a root layout client component or standard useEffect lifecycle hook.

app/providers.tsx
'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().

worker.js
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 TYPES

Click each schema card to view full TypeScript interfaces and configuration structures.

interface ShieldOptions {...}
{ action?: 'sandbox' | 'remove' | 'blank'; sandboxFlags?: string; // Default: 'allow-scripts allow-same-origin' sandboxUntrusted?: boolean; // Default: true blockTrackingPixels?: boolean; // Default: true blockClickjackingOverlays?: boolean; // Default: true matchDimensions?: boolean; // Default: false trustedDomains?: string[]; // e.g. ['youtube.com', 'stripe.com'] adDomains?: string[]; // e.g. ['doubleclick.net', 'popads.net'] onBlocked?: (event: BlockEvent, iframe: HTMLIFrameElement) => void; debug?: boolean; }
interface BlockEvent {...}
{ timestamp: number; // Epoch milliseconds src: string; // URL of intercepted frame reason: | 'known_ad_network' | 'hidden_tracking_iframe' | 'clickjacking_transparent_overlay' | 'untrusted_third_party'; matched?: string; // Matched domain or dimension rule action: 'sandbox' | 'remove' | 'blank'; }
interface ShieldStats {...}
{ scanned: number; // Total iframe elements inspected blocked: number; // Hostile or tracking frames blocked sandboxed: number; // Untrusted frames restricted history: BlockEvent[]; // Chronological event log }

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.