Skip to content

Commit e8e3681

Browse files
alan-agius4atscott
authored andcommitted
fix(platform-browser): set nonce attribute in a platform compatible way (#49624)
Setting the `nonce` attribute using the property is not supported by Domino. This change update the usage to use `setAttribute` and also add a test to verify that the `nonce` is set when it should. PR Close #49624
1 parent e994608 commit e8e3681

File tree

4 files changed

+12
-6
lines changed

4 files changed

+12
-6
lines changed

packages/core/test/acceptance/csp_spec.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ describe('CSP integration', () => {
2222

2323
for (let i = 0; i < styles.length; i++) {
2424
const style = styles[i];
25-
if (style.textContent?.includes('--csp-test-var') && style.nonce) {
26-
nonces.push(style.nonce);
25+
const nonce = style.getAttribute('nonce');
26+
if (nonce && style.textContent?.includes('--csp-test-var')) {
27+
nonces.push(nonce);
2728
}
2829
}
2930

packages/platform-browser/src/dom/dom_renderer.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -327,8 +327,7 @@ class ShadowDomRenderer extends DefaultDomRenderer2 {
327327
const styleEl = document.createElement('style');
328328

329329
if (nonce) {
330-
// Uses a keyed write to avoid issues with property minification.
331-
styleEl['nonce'] = nonce;
330+
styleEl.setAttribute('nonce', nonce);
332331
}
333332

334333
styleEl.textContent = style;

packages/platform-browser/src/dom/shared_styles_host.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,7 @@ export class SharedStylesHost implements OnDestroy {
147147
const styleEl = this.doc.createElement('style');
148148

149149
if (this.nonce) {
150-
// Uses a keyed write to avoid issues with property minification.
151-
styleEl['nonce'] = this.nonce;
150+
styleEl.setAttribute('nonce', this.nonce);
152151
}
153152

154153
styleEl.textContent = style;

packages/platform-browser/test/dom/shared_styles_host_spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,12 @@ import {expect} from '@angular/platform-browser/testing/src/matchers';
5454
ssh.ngOnDestroy();
5555
expect(someHost.innerHTML).toEqual('');
5656
});
57+
58+
it(`should add 'nonce' attribute when a nonce value is provided`, () => {
59+
ssh = new SharedStylesHost(doc, 'app-id', '{% nonce %}');
60+
ssh.addStyles(['a {};']);
61+
ssh.addHost(someHost);
62+
expect(someHost.innerHTML).toEqual('<style nonce="{% nonce %}">a {};</style>');
63+
});
5764
});
5865
}

0 commit comments

Comments
 (0)