script.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /**
  2. * @license
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. import { unwrapResourceUrl } from '../../internals/resource_url_impl';
  6. import { unwrapScript } from '../../internals/script_impl';
  7. /** Returns CSP nonce, if set for any script tag. */
  8. function getScriptNonceFromWindow(win) {
  9. const doc = win.document;
  10. // document.querySelector can be undefined in non-browser environments.
  11. const script = doc.querySelector?.('script[nonce]');
  12. if (script) {
  13. // Try to get the nonce from the IDL property first, because browsers that
  14. // implement additional nonce protection features (currently only Chrome) to
  15. // prevent nonce stealing via CSS do not expose the nonce via attributes.
  16. // See https://github.com/whatwg/html/issues/2369
  17. return script['nonce'] || script.getAttribute('nonce') || '';
  18. }
  19. return '';
  20. }
  21. /** Propagates CSP nonce to dynamically created scripts. */
  22. function setNonceForScriptElement(script) {
  23. const win = script.ownerDocument && script.ownerDocument.defaultView;
  24. const nonce = getScriptNonceFromWindow(win || window);
  25. if (nonce) {
  26. script.setAttribute('nonce', nonce);
  27. }
  28. }
  29. /** Sets textContent from the given SafeScript. */
  30. export function setTextContent(script, v) {
  31. script.textContent = unwrapScript(v);
  32. setNonceForScriptElement(script);
  33. }
  34. /** Sets the Src attribute using a TrustedResourceUrl */
  35. export function setSrc(script, v) {
  36. script.src = unwrapResourceUrl(v);
  37. setNonceForScriptElement(script);
  38. }