parseURL.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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) {// URL parsing failed, do nothing.
  25. // We will still proceed to see if we can recover using `resourceQuery`
  26. }
  27. if (scriptSourceURL) {
  28. options = scriptSourceURL;
  29. options.fromCurrentScript = true;
  30. }
  31. }
  32. return options;
  33. }
  34. export default parseURL;