Source: inline.js

  1. /**
  2. * This module provides utilities for working with inlined content.
  3. *
  4. * @module inline
  5. */
  6. /**
  7. * Extract the content from a data URL as a string, decoding it from Base64
  8. * if necessary. Useful for working with content scripts that have been
  9. * encoded with `@rollup/plugin-url`.
  10. * @param {string} dataUrl - The data URL.
  11. * @returns {string} - The content of the URL.
  12. */
  13. export function dataUrlToString(dataUrl) {
  14. if(!dataUrl.startsWith("data:")) {
  15. throw new Error("Incorrectly formatted data URL.");
  16. }
  17. const commaIndex = dataUrl.indexOf(",");
  18. if(commaIndex < 0) {
  19. throw new Error("Incorrectly formatted data URL.");
  20. }
  21. // Not currently checking that the MIME type is valid
  22. const dataUrlMimeTypeAndEncoding = dataUrl.substring(0, commaIndex);
  23. let content = dataUrl.substring(commaIndex + 1, dataUrl.length);
  24. if(dataUrlMimeTypeAndEncoding.endsWith("base64")) {
  25. content = atob(content);
  26. }
  27. return content;
  28. }
  29. /**
  30. * Convert a data URL to a blob object URL. Useful for working with HTML
  31. * documents that have been encoded with `@rollup/plugin-url`.
  32. * @param {*} dataUrl - The data URL.
  33. * @returns {string} - A blob object URL.
  34. */
  35. export function dataUrlToBlobUrl(dataUrl) {
  36. return URL.createObjectURL(new Blob([ dataUrlToString(dataUrl) ]));
  37. }