Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

The nonce attribute

The nonce attribute holds a textual cryptographic value used by Content Security Policy (CSP). The element.nonce property exposes it to scripts even when the browser hides the attribute value.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

nonce="value"; element.nonce; element.nonce = value

nonce represents a cryptographic number used once that Content Security Policy (CSP) can use when deciding whether to allow a resource fetch. The attribute alone does not define a security policy.

Distinguish the HTML nonce attribute from the DOM property element.nonce. Setting the attribute updates the internal [[CryptographicNonce]] value. Reading the property returns that value, but assigning to the property does not update the attribute.

When an element becomes browsing-context connected and the CSP list contains a policy delivered through an HTTP header, the browser empties its nonempty attribute while preserving the internal nonce value. This limits leakage through CSS selectors; scripts can still read element.nonce. Consequently, getAttribute('nonce') is not a reliable way to read the current nonce value.

The example demonstrates the attribute/property distinction on a detached element. Its fixed values are for demonstration only, not for securing content.

Examples

const element = document.createElement('script');
element.setAttribute('nonce', 'demo-only');
console.log(element.nonce);
element.nonce = 'changed-demo-only';
console.log(element.nonce);
console.log(element.getAttribute('nonce'));

Result

demo-only
changed-demo-only
demo-only

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources