Skip to content

Commit 19f57a3

Browse files
committed
Update docs.
1 parent 4ff5d3d commit 19f57a3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

README.md

+44
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,50 @@ Deferring the display of markup is typically done in the following usage pattern
100100

101101
- The first time a user visits a page that contains a time-consuming piece of markup to generate, a loading indicator is displayed. When the markup is finished building on the server, it's stored in memcache and sent to the browser to replace the include-fragment loader. Subsequent visits to the page render the cached markup directly, without going through a include-fragment element.
102102

103+
### CSP Trusted Types
104+
105+
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 server response before it is inserted into the page:
106+
107+
```ts
108+
import { setCSPTrustedTypesPolicy } from "include-fragment-element";
109+
import DOMPurify from "dompurify"; // Using https://github.com/cure53/DOMPurify
110+
111+
// This policy removes all HTML markup except links.
112+
const policy = trustedTypes.createPolicy("links-only", {
113+
createHTML: (htmlText: string) => {
114+
return DOMPurify.sanitize(htmlText, {
115+
ALLOWED_TAGS: ["a"],
116+
ALLOWED_ATTR: ["href"],
117+
RETURN_TRUSTED_TYPE: true,
118+
});
119+
},
120+
});
121+
setCSPTrustedTypesPolicy(policy);
122+
```
123+
124+
The policy has access to the server response object. Due to platform constraints, only synchronous from the response can be used in the policy:
125+
126+
```ts
127+
import { setCSPTrustedTypesPolicy } from "include-fragment-element";
128+
129+
const policy = trustedTypes.createPolicy("require-server-header", {
130+
createHTML: (htmlText: string, response: Response) => {
131+
if (response.headers.get("X-Server-Sanitized") !== "sanitized=true") {
132+
// Note: this will reject the contents, but the error may be caught before it shows in the JS console.
133+
throw new Error("Rejecting HTML that was not marked by the server as sanitized.");
134+
}
135+
return htmlText;
136+
},
137+
});
138+
setCSPTrustedTypesPolicy(policy);
139+
```
140+
141+
Note that:
142+
143+
- Only a single policy can be set, shared by all `IncludeFragmentElement` fetches.
144+
- You should call `setCSPTrustedTypesPolicy()` ahead of any other load of `include-fragment-element` in your code.
145+
146+
If your policy itself requires asynchronous work to construct, you can also pass a `Promise<TrustedTypePolicy>`. Pass `null` to remove the policy.
103147

104148
## Relation to Server Side Includes
105149

0 commit comments

Comments
 (0)