How does Content Security Policy (CSP) work with HTML5?
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.
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.

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:

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'
:

<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 byframe-ancestors
to prevent clickjacking<video>
and<audio>
: Their sources are checked undermedia-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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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.

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

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

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

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.

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

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.
