parseURL.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import getCurrentScriptSource from "./getCurrentScriptSource.js";
  2. /**
  3. * @param {string} resourceQuery
  4. * @returns {{ [key: string]: string | boolean }}
  5. */
  6. function parseURL(resourceQuery) {
  7. /** @type {{ [key: string]: string }} */
  8. var options = {};
  9. if (typeof resourceQuery === "string" && resourceQuery !== "") {
  10. var searchParams = resourceQuery.slice(1).split("&");
  11. for (var i = 0; i < searchParams.length; i++) {
  12. var pair = searchParams[i].split("=");
  13. options[pair[0]] = decodeURIComponent(pair[1]);
  14. }
  15. } else {
  16. // Else, get the url from the <script> this file was called with.
  17. var scriptSource = getCurrentScriptSource();
  18. var scriptSourceURL;
  19. try {
  20. // The placeholder `baseURL` with `window.location.href`,
  21. // is to allow parsing of path-relative or protocol-relative URLs,
  22. // and will have no effect if `scriptSource` is a fully valid URL.
  23. scriptSourceURL = new URL(scriptSource, self.location.href);
  24. } catch (error) {
  25. // URL parsing failed, do nothing.
  26. // We will still proceed to see if we can recover using `resourceQuery`
  27. }
  28. if (scriptSourceURL) {
  29. options = scriptSourceURL;
  30. options.fromCurrentScript = true;
  31. }
  32. }
  33. return options;
  34. }
  35. export default parseURL;