CodeBlanks Logo Icon CodeBlanks

CSP meta

HTML course · Expert · Lesson 26/39

Learn basic <meta http-equiv="Content-Security-Policy"> usage.

What is Content-Security-Policy?

Content-Security-Policy (CSP) tells the browser which sources a page may load scripts, images and styles from. Even if malicious code is injected into the page, CSP blocks loads from unapproved sources.

CSP can be sent as an HTTP header or written into HTML with a meta tag. In this project we'll use the meta approach.

The core of CSP is a list of directives like default-src, img-src and style-src.

Add CSP with meta http-equiv

To add CSP to HTML, write http-equiv="Content-Security-Policy" on a meta tag. The content attribute carries the directive list.

Example: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:;">

Here default-src 'self' says all sources must come from the same origin. 'self' must be in single quotes; bare self is parsed wrong.

Exercise Add the CSP meta tag to head

Take the previous lesson's page. Inside <head>, after viewport, add a CSP meta tag:

  • http-equiv="Content-Security-Policy"
  • content includes: default-src 'self', img-src 'self' data: and style-src 'self' 'unsafe-inline'

The 'self' values must be in single quotes.

Show example solution
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'">
    <title>Secure Bank - Sign in</title>
  </head>
  <body>
    <h1>Secure Bank</h1>
    <p>Please sign in with your user code.</p>
    <p><a href="https://help.securebank.example/signing-in" target="_blank" rel="noopener noreferrer">Help center</a></p>
  </body>
</html>

Test yourself

  1. Which security threat does CSP mitigate?

    • It measures page load speed
    • It blocks scripts from malicious sources
    • It sets the page color palette
    • It makes links open in a new tab
    Show answer

    It blocks scripts from malicious sources — Correct. CSP blocks scripts and resources from unapproved sources.

  2. Complete the default-src value

    <meta http-equiv="Content-Security-Policy" content="default-src ____; img-src 'self' data:; style-src 'self' 'unsafe-inline'">
    Show answer
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'">
  3. Match each CSP directive to its meaning

    default-src
    default for all sources
    img-src
    image sources
    style-src
    style sources
    script-src
    script sources

All lessons in Expert