Skip to content

Commit 44334ec

Browse files
authored
Fixed CSP support. Apply the nonce attribute before appending the element to the head. Added a test (#613)
1 parent f76ceab commit 44334ec

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

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": "1301B"
134+
"gzip": "1300B"
135135
},
136136
"./dist/goober.cjs": {
137137
"gzip": "1300B"

src/core/__tests__/get-sheet.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,28 @@ describe('getSheet', () => {
2323
expect(sheet === second).toBeTruthy();
2424
});
2525

26+
it('applies nonce from window.__nonce__', () => {
27+
const sheet = getSheet();
28+
const style = sheet.parentElement;
29+
const prevAttr = style.getAttribute('nonce');
30+
const hadAttr = style.hasAttribute('nonce');
31+
const prevNonce = window.__nonce__;
32+
33+
style.removeAttribute('nonce');
34+
delete window.__nonce__;
35+
36+
window.__nonce__ = 'secure-nonce';
37+
getSheet();
38+
39+
expect(style.getAttribute('nonce')).toEqual('secure-nonce');
40+
41+
if (prevAttr != null) style.setAttribute('nonce', prevAttr);
42+
else if (!hadAttr) style.removeAttribute('nonce');
43+
44+
if (prevNonce === undefined) delete window.__nonce__;
45+
else window.__nonce__ = prevNonce;
46+
});
47+
2648
it('server side', () => {
2749
const bkp = global.document;
2850
delete global.document;

src/core/get-sheet.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@ export let getSheet = (target) => {
1414
// We're doing a querySelector because the <head> element doesn't implemented the getElementById api
1515
let el =
1616
(target ? target.querySelector('#' + GOOBER_ID) : window[GOOBER_ID]) ||
17-
Object.assign((target || document.head).appendChild(document.createElement('style')), {
17+
Object.assign(document.createElement('style'), {
1818
innerHTML: ' ',
1919
id: GOOBER_ID
2020
});
21-
if (window.__nonce__) el.setAttribute('nonce', window.__nonce__);
21+
el.nonce = window.__nonce__;
22+
if (!el.parentNode) (target || document.head).appendChild(el);
2223
return el.firstChild;
2324
}
2425

0 commit comments

Comments
 (0)