Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/Dom/dynamicCSS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function injectCSS(css: string, option: Options = {}) {
if (csp?.nonce) {
styleNode.nonce = csp?.nonce;
}
styleNode.innerHTML = css;
styleNode.textContent = css;

const container = getContainer(option);
const { firstChild } = container;
Expand Down Expand Up @@ -177,8 +177,8 @@ export function updateCSS(
existNode.nonce = option.csp?.nonce;
}

if (existNode.innerHTML !== css) {
existNode.innerHTML = css;
if (existNode.textContent !== css) {
existNode.textContent = css;
}

return existNode;
Expand Down
35 changes: 35 additions & 0 deletions tests/dynamicCSS.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,41 @@ describe('dynamicCSS', () => {
expect(document.querySelector('style').nonce).toEqual('light');
});

it('does not assign CSS through the innerHTML sink', () => {
const innerHTMLDescriptor = Object.getOwnPropertyDescriptor(
HTMLStyleElement.prototype,
'innerHTML',
);

Object.defineProperty(HTMLStyleElement.prototype, 'innerHTML', {
configurable: true,
set() {
throw new TypeError(
"This document requires 'TrustedHTML' assignment.",
);
},
});

try {
const style = injectCSS(TEST_STYLE);
const managedStyle = updateCSS(TEST_STYLE, 'trusted-types');

expect(style.textContent).toEqual(TEST_STYLE);
expect(() => updateCSS('.light {}', 'trusted-types')).not.toThrow();
expect(managedStyle.textContent).toEqual('.light {}');
} finally {
if (innerHTMLDescriptor) {
Object.defineProperty(
HTMLStyleElement.prototype,
'innerHTML',
innerHTMLDescriptor,
);
} else {
delete HTMLStyleElement.prototype.innerHTML;
}
}
});

describe('prepend', () => {
function testPrepend() {
const head = document.querySelector('head');
Expand Down