Skip to content
This repository was archived by the owner on Jan 9, 2025. It is now read-only.

Commit 0e40021

Browse files
committed
Update docs
1 parent e47453e commit 0e40021

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,30 @@ render(html`<div>${until(request, timeout, loading)}</div>`)
245245
// ^ renders <div>Loading...</div>
246246
// After 2000ms will render <div>Failed to load</div>
247247
```
248+
249+
### CSP Trusted Types
250+
251+
You can call `setCSPTrustedTypesPolicy(policy: TrustedTypePolicy | Promise<TrustedTypePolicy> | null)` from JavaScript to set a [CSP trusted types policy](https://web.dev/trusted-types/), which can perform (synchronous) filtering or rejection of the rendered template:
252+
253+
```ts
254+
import {setCspTrustedTypePolicy} from "@github/jtml";
255+
import DOMPurify from "dompurify"; // Using https://github.com/cure53/DOMPurify
256+
257+
// This policy removes all HTML markup except links.
258+
const policy = trustedTypes.createPolicy("links-only", {
259+
createHTML: (htmlText: string) => {
260+
return DOMPurify.sanitize(htmlText, {
261+
ALLOWED_TAGS: ["a"],
262+
ALLOWED_ATTR: ["href"],
263+
RETURN_TRUSTED_TYPE: true,
264+
});
265+
},
266+
});
267+
setCSPTrustedTypesPolicy(policy);
268+
```
269+
270+
Note that:
271+
272+
- Only a single policy can be set, shared by all `render` and `unsafeHTML` calls.
273+
- You should call `setCSPTrustedTypesPolicy()` ahead of any other call of `@github/jtml` in your code.
274+
- Not all browsers [support the trusted types API in JavaScript](https://caniuse.com/mdn-api_trustedtypes). You may want to use the [recommended tinyfill](https://github.com/w3c/trusted-types#tinyfill) to construct a policy without causing issues in other browsers.

0 commit comments

Comments
 (0)