script.js 1.8 KB

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