Skip to content

Commit 2d9c308

Browse files
authored
feat: add nonce() for CSP support (#612)
1 parent 5f0b439 commit 2d9c308

3 files changed

Lines changed: 18 additions & 4 deletions

File tree

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ It's a pun on the tagline.
6868
- [Sharing Style](#sharing-style)
6969
- [Autoprefixer](#autoprefixer)
7070
- [TypeScript](#typescript)
71+
- [Content Security Policy (CSP)](#content-security-policy-csp)-
7172
- [Browser Support](#browser-support)
7273
- [Contributing](#contributing)
7374

@@ -704,6 +705,18 @@ Usage:
704705
- [x] target/extract from elements other than `<head>`
705706
- [x] [vendor prefixing](#autoprefixer)
706707

708+
# Content Security Policy (CSP)
709+
710+
goober supports Content Security Policy nonces for inline styles. Set `window.__nonce__` before loading the library:
711+
712+
```js
713+
<script nonce="your-nonce-here">
714+
window.__nonce__ = 'your-nonce-here';
715+
</script>
716+
```
717+
718+
The nonce will be added to goober's `<style>` element.
719+
707720
# Sharing style
708721

709722
There are a couple of ways to effectively share/extend styles across components.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@
131131
"typings": "./goober.d.ts",
132132
"filesize": {
133133
"./dist/goober.modern.js": {
134-
"gzip": "1300B"
134+
"gzip": "1301B"
135135
},
136136
"./dist/goober.cjs": {
137137
"gzip": "1300B"

src/core/get-sheet.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ export let getSheet = (target) => {
1212
if (typeof window === 'object') {
1313
// Querying the existing target for a previously defined <style> tag
1414
// We're doing a querySelector because the <head> element doesn't implemented the getElementById api
15-
return (
15+
let el =
1616
(target ? target.querySelector('#' + GOOBER_ID) : window[GOOBER_ID]) ||
1717
Object.assign((target || document.head).appendChild(document.createElement('style')), {
1818
innerHTML: ' ',
1919
id: GOOBER_ID
20-
})
21-
).firstChild;
20+
});
21+
if (window.__nonce__) el.setAttribute('nonce', window.__nonce__);
22+
return el.firstChild;
2223
}
2324

2425
return target || ssr;

0 commit comments

Comments
 (0)