How to Stop Userscripts from Running in Iframes?

Preventing userscripts from executing inside <iframe> elements requires a combination of server-side security headers, client-side JavaScript checks, and proper userscript metadata configuration. While userscripts (managed by extensions like Tampermonkey or Violentmonkey) run at a browser-extension privilege level, web developers can use frame-busting logic and Content Security Policies to restrict subframe interactions, while script authors can use specific header directives to restrict execution strictly to the top-level window.

Preventing Execution via Script Metadata (For Userscript Authors)

If you are writing or configuring a userscript and want to prevent it from running inside any embedded frames, the standard solution is to use the @noframes directive in the script’s metadata block.

// ==UserScript==
// @name         My Userscript
// @match        https://example.com/*
// @noframes
// ==UserScript==

When the @noframes directive is present, the userscript manager automatically restricts execution to the top-level document (window.top), skipping any <iframe> elements loaded within the page.

Detecting and Blocking Frame Execution (For Web Developers)

If you are a web developer attempting to mitigate unauthorized script behavior or frame manipulation within embedded frames, standard JavaScript frame detection can help isolate your context.

1. Frame-Busting Checks

You can check whether the current execution context is inside an iframe by comparing window.self to window.top:

if (window.self !== window.top) {
    // Code is running inside an iframe
    // You can halt sensitive operations or alert the user
}

2. Utilizing the sandbox Attribute

When embedding an iframe on your own site, using the sandbox attribute restricts what scripts can do within the frame:

<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>

Omitting allow-same-origin or restricting specific permissions prevents embedded frames from accessing the parent document’s DOM, significantly limiting the impact of potential script injections within subframes.