MDN self-hosted library · e01.org

Content Security Policy (CSP)

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
  <script src="https://evil.example.com/hacker.js"></script>
html
  <script>
    console.log("You've been hacked!");
  </script>
html
  <img
    onmouseover="console.log(`You've been hacked!`)"
    src="thumbnail.jpg"
    alt="" />
html
  <iframe src="javascript:console.log(`You've been hacked!`)"></iframe>
js
  eval("console.log(`You've been hacked!`)");
js
function content(nonce) {
  return `
    <script nonce="${nonce}" src="/main.js"></script>
    <script nonce="${nonce}">console.log("hello!");</script>
    <h1>Hello world</h1> 
    `;
}

app.get("/", (req, res) => {
  const nonce = crypto.randomUUID();
  res.setHeader("Content-Security-Policy", `script-src 'nonce-${nonce}'`);
  res.send(content(nonce));
});
js
const hash1 = "sha256-ex2O7MWOzfczthhKm6azheryNVoERSFrPrdvxRtP8DI=";
const hash2 = "sha256-H/eahVJiG1zBXPQyXX0V6oaxkfiBdmanvfG9eZWSuEc=";

const csp = `script-src '${hash1}' '${hash2}'`;
const content = `
  <script src="./main.js" integrity="${hash2}"></script>
  <script>console.log("hello!");</script>
    <h1>Hello world</h1> 
    `;

app.get("/", (req, res) => {
  res.setHeader("Content-Security-Policy", csp);
  res.send(content);
});
html
  <script>
    console.log("Hello from an inline script");
  </script>
html
  <img src="x" onerror="console.log('Hello from an inline event handler')" />
html
  <a href="javascript:console.log('Hello from a javascript: URL')">Click me</a>