# CSP & Sandboxed Code Execution ## Extension CSP Restrictions Chrome Extensions enforce a strict Content Security Policy that cannot be relaxed for extension pages (popup, side panel, options, new tab, etc.). Blocked by default: - `eval()`, `new Function()`, `setTimeout("string")` - Inline ` ``` In `popup.js`: ```js document.getElementById('btn').addEventListener('click', () => { // Handle click }); ``` ## Executing User Code (Code Playground Pattern) If you need to execute arbitrary code (e.g., a CodePen-like playground), you MUST use one of these approaches. **Extension CSP completely blocks `eval()`, `new Function()`, and inline scripts in normal extension pages.** There is no way around this — you need sandboxing. ### Option 1: Sandboxed Page in Manifest (Recommended) Declare a sandboxed page in manifest.json. Sandboxed pages have a relaxed CSP that allows `eval()` and inline scripts, but they cannot access chrome.* APIs. ```json { "sandbox": { "pages": ["sandbox.html"] } } ``` Use an iframe in your extension page to embed the sandbox: ```html ``` **CRITICAL:** Communication between the extension page and the sandboxed iframe MUST use `postMessage`. You CANNOT access `iframe.contentDocument` or `iframe.contentWindow.document` directly — this will throw: ``` SecurityError: Blocked a frame with origin "chrome-extension://..." from accessing a cross-origin frame. ``` Correct pattern: ```js // playground.js — send code to sandbox const iframe = document.getElementById('preview'); iframe.contentWindow.postMessage({ html: htmlCode, css: cssCode, js: jsCode }, '*'); // sandbox.js — receive and execute window.addEventListener('message', (event) => { const { html, css, js } = event.data; // Clear previous content document.body.innerHTML = ''; document.head.querySelectorAll('style.user-style').forEach(s => s.remove()); // Apply HTML const container = document.createElement('div'); container.innerHTML = html; document.body.appendChild(container); // Apply CSS const style = document.createElement('style'); style.className = 'user-style'; style.textContent = css; document.head.appendChild(style); // Execute JS (eval is allowed in sandbox!) try { eval(js); } catch (e) { const errEl = document.createElement('pre'); errEl.style.color = 'red'; errEl.textContent = e.message; document.body.appendChild(errEl); } }); ``` ### Option 2: Blob URL in iframe Create a self-contained HTML document via blob URL: ```js function updatePreview(htmlCode, cssCode, jsCode) { const html = `
${htmlCode}