NoScript等JavaScript拦截扩展如何拦截内联脚本及后续注入脚本?
Great question! Let's break down how extensions like NoScript and ScriptSafe handle both inline scripts and dynamically injected remote scripts—these are two distinct challenges, and they use a mix of early execution hooks, DOM manipulation, and browser API integrations to pull it off.
拦截内联脚本的核心机制
As you noticed, webRequest can't touch inline scripts because there's no network request involved. Instead, these extensions rely on early-running content scripts (set to run_at: "document_start") to intercept inline scripts before they ever get a chance to execute. Here's the playbook:
Rewrite critical DOM methods first: Before the page's DOM starts loading, the extension overrides methods like
document.write,innerHTML, andinsertAdjacentHTML—common ways inline scripts get injected dynamically. When the page tries to use these methods to add a<script>tag without asrcattribute, the extension filters out the script content or modifies it so the browser ignores it (e.g., changing thetypeattribute totext/plain).Pre-register MutationObservers: The extension sets up a
MutationObserverbefore the DOM is built. This observer watches for any new nodes being added to the document. As soon as a<script>tag without asrcis detected, the observer either removes the tag entirely or tweaks its attributes to prevent execution (like renaming the tag to something non-functional, though changing thetypeis more reliable).Inject strict Content Security Policy (CSP) headers: Many of these extensions also inject a CSP rule into the page. A rule like
script-src 'self' trusted-domain.comblocks all inline scripts by default (unless they have a valid nonce or hash, which untrusted scripts won't have). This is a browser-enforced block, which is far more robust than DOM manipulation alone.
阻止页面加载后注入的受限域名脚本
Stopping scripts injected minutes after page load requires persistent monitoring and layered checks:
Persistent MutationObserver: The same observer used for inline scripts doesn't shut down after page load—it keeps watching for new
<script>tags added dynamically. If a tag'ssrcpoints to a blocked domain, the observer removes the tag immediately, before the browser can start fetching the script.Augmented
webRequestinterception: WhilewebRequestcan't catch inline scripts, it can catch network requests from dynamically injected remote scripts. The extension usesonBeforeRequestto block any request to a restricted domain, regardless of whether the script tag was added on page load or 10 minutes later. This acts as a safety net if the DOM observer misses something.Override script creation methods: The extension rewrites
document.createElement('script')andElement.setAttribute('src'). When the page tries to create a script tag pointing to a blocked domain, the modified methods either refuse to set thesrcattribute, or redirect it to a harmless placeholder, preventing the request from ever being made.
内容的提问来源于stack exchange,提问作者Mark Howard

