Table of Contents
2. External Resource Control
3. Use with HTML5 APIs and Features
4. Reporting Violations
Home Web Front-end H5 Tutorial How does Content Security Policy (CSP) work with HTML5?

How does Content Security Policy (CSP) work with HTML5?

Aug 30, 2025 am 01:29 AM
html5 csp

CSP enhances HTML5 security by defining trusted content sources to prevent XSS, clickjacking, and code injection. 1. It restricts inline scripts and styles by blocking them unless 'unsafe-inline', nonces, or hashes are used. 2. It controls external resources via directives like script-src, img-src, and style-src to allow only trusted origins. 3. It integrates with HTML5 features by governing Web Workers (worker-src), WebSocket connections (connect-src), iframe embedding (frame-ancestors), and media (media-src). 4. It enables violation reporting through report-uri or report-to to monitor and fix policy breaches. CSP is implemented via HTTP headers or meta tags and acts as a critical security layer that modern HTML5 applications must adopt to ensure only trusted code and assets are executed.

How does Content Security Policy (CSP) work with HTML5?

Content Security Policy (CSP) works with HTML5 by providing a security layer that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks. It does this by allowing developers to define which sources of content are allowed to be loaded and executed within an HTML5 document.

How does Content Security Policy (CSP) work with HTML5?

CSP is implemented through HTTP headers (like Content-Security-Policy) or via a <meta> tag in the HTML5 document. When a browser loads a page, it reads the CSP and enforces the rules before loading any resources such as scripts, styles, images, or iframes.

Here’s how CSP integrates with key aspects of HTML5:

How does Content Security Policy (CSP) work with HTML5?

1. Inline Script and Style Restrictions

HTML5 allows inline scripts and styles (e.g., <script></script>, onclick="", <style></style>), but these are common vectors for XSS. CSP blocks them by default unless explicitly allowed.

For example, this inline script would be blocked if CSP doesn’t permit 'unsafe-inline':

How does Content Security Policy (CSP) work with HTML5?
<button onclick="alert('hacked')">Click me</button>

To allow inline scripts (not recommended), you'd use:

Content-Security-Policy: script-src 'unsafe-inline';

But a better approach is to use nonces or hashes:

<script nonce="2726c7f26c">
  alert('Allowed script');
</script>

With CSP:

Content-Security-Policy: script-src 'nonce-2726c7f26c';

2. External Resource Control

CSP lets you specify trusted sources for loading resources:

  • Scripts (script-src)
  • Styles (style-src)
  • Images (img-src)
  • Fonts (font-src)
  • Frames (frame-src)
  • And more

Example:

Content-Security-Policy: default-src 'self'; img-src *; script-src trusted.cdn.com

This means:

  • Load all resources from the same origin by default
  • Allow images from any domain
  • Only allow scripts from trusted.cdn.com

3. Use with HTML5 APIs and Features

CSP also affects modern HTML5 features:

  • Web Workers: Controlled via worker-src
  • WebSocket connections: Governed by connect-src
  • <iframe> embedding: Restricted by frame-ancestors to prevent clickjacking
  • <video> and <audio>: Their sources are checked under media-src

For example, to prevent your site from being embedded in an iframe:

Content-Security-Policy: frame-ancestors 'none';

4. Reporting Violations

CSP supports a reporting mechanism using report-uri or report-to to collect policy violations:

Content-Security-Policy: default-src 'self'; report-uri /csp-report-endpoint

When a browser blocks a resource due to CSP, it sends a JSON report to the specified endpoint, helping developers detect and fix issues.


In summary, CSP enhances HTML5 security by giving fine-grained control over which resources the browser can load and execute. It works hand-in-hand with HTML5’s rich feature set to reduce the risk of malicious content execution, especially by discouraging unsafe practices like inline JavaScript.

It’s not part of the HTML5 spec per se, but it’s a critical companion standard that modern HTML5 applications should implement to stay secure.

Basically, CSP tells the browser: “Only run code and load assets from places I trust”—and the browser enforces that, even if attackers manage to inject HTML or script tags.

The above is the detailed content of How does Content Security Policy (CSP) work with HTML5?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the aside element for in HTML5? What is the aside element for in HTML5? Aug 12, 2025 pm 04:37 PM

Theelementshouldbeusedforcontenttangentiallyrelatedtothemaincontent,suchassidebars,pullquotes,definitions,advertisements,orrelatedlinks;2.Itcanbeplacedinsideoroutsideanarticledependingoncontext;3.ItisasemanticelementthatenhancesaccessibilityandSEObyp

How to create a simple HTML5 webpage How to create a simple HTML5 webpage Aug 12, 2025 am 11:51 AM

To create a simple HTML5 web page, you need to first use the declaration document type, and then build a basic structure containing, and, which sets the character encoding, viewport and title, add visible content such as title, paragraph, link, pictures and lists. Save it as a .html file and open it directly in the browser for viewing, without server support. This is the basis of a complete and effective HTML5 page.

How do you use the autofocus attribute in HTML5? How do you use the autofocus attribute in HTML5? Aug 14, 2025 pm 06:47 PM

Theautofocusattributeautomaticallyfocusesaformelementwhenapageloads.2.Itisabooleanattribute,sonovalueisneeded—justincludeautofocusinthetag.3.Onlyoneelementperpageshoulduseittoavoidunpredictablebehavior.4.Itworksoninput,textarea,select,andbuttonelemen

How to use the nav tag for navigation links in HTML5 How to use the nav tag for navigation links in HTML5 Aug 15, 2025 am 05:55 AM

ThetaginHTML5isusedtodefineasectionofmajornavigationlinks,providingsemanticstructureandimprovingaccessibilityandSEO;itshouldwrapprimarynavigationelementslikemenusortablesofcontents,noteverylinkonapage,andcanbeenhancedwithARIAlabelssuchasaria-label=&q

What is a definition list in HTML5? What is a definition list in HTML5? Aug 20, 2025 pm 02:01 PM

AdefinitionlistinHTML5iscreatedusingtheelementtogroupterms()withtheirdefinitions(),allowingmultipletermstoshareadefinitionoratermtohavemultipledefinitions,makingitidealforFAQs,glossaries,metadata,andcontactdetailswhileimprovingaccessibilityandSEOthro

How to create a custom checkbox with HTML5 How to create a custom checkbox with HTML5 Aug 16, 2025 am 07:05 AM

To create a custom checkbox, you must first use an HTML structure with label to ensure accessibility; 2. Hide the default checkbox through CSS but retain its functionality; 3. Use pseudo-elements and pseudo-classes to draw the selected state on the custom .checkmark elements; 4. Add hover, focus and select styles to enhance interactive feedback; 5. Keep native inputs present to support keyboard navigation and screen readers, and ultimately achieve beautiful and accessible custom checkboxes.

What is the figure element and how is it used with figcaption in HTML5? What is the figure element and how is it used with figcaption in HTML5? Aug 20, 2025 pm 02:06 PM

TheelementinHTML5isusedtomarkupself-containedcontentlikeimages,diagrams,orcodesnippetsthatcanstandindependentlywithinadocument.Itcanbepairedwiththeoptionalelementtoprovideacaptionortitle,whichmayappearasthefirstorlastchildinside.Thiscombinationenhanc

How to preload content with rel='preload' in HTML5? How to preload content with rel='preload' in HTML5? Aug 20, 2025 pm 04:12 PM

rel="preload" is used to load key resources in advance to improve page performance. 1. Use syntax and specify the as attribute; 2. Preload key resources such as fonts, style sheets, scripts, pictures, etc., and the font needs to be added crossorigin; 3. It can be loaded according to conditions in combination with media attributes; 4. Follow best practices such as loading only key resources on the first screen, avoiding excessive use, and correctly setting type and crossorigin; 5. Modern browsers widely support it, and can dynamically add or perform gradual enhancement processing through JavaScript to ensure that the page still works normally when it is not supported.

See all articles