getCurrentScriptSource.js 1.1 KB

123456789101112131415161718192021222324252627282930
  1. /**
  2. * Gets the source (i.e. host) of the script currently running.
  3. * @returns {string}
  4. */
  5. function getCurrentScriptSource() {
  6. // `document.currentScript` is the most accurate way to get the current running script,
  7. // but is not supported in all browsers (most notably, IE).
  8. if ('currentScript' in document) {
  9. // In some cases, `document.currentScript` would be `null` even if the browser supports it:
  10. // e.g. asynchronous chunks on Firefox.
  11. // We should not fallback to the list-approach as it would not be safe.
  12. if (document.currentScript == null) return;
  13. return document.currentScript.getAttribute('src');
  14. }
  15. // Fallback to getting all scripts running in the document,
  16. // and finding the last one injected.
  17. else {
  18. const scriptElementsWithSrc = Array.prototype.filter.call(
  19. document.scripts || [],
  20. function (elem) {
  21. return elem.getAttribute('src');
  22. }
  23. );
  24. if (!scriptElementsWithSrc.length) return;
  25. const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
  26. return currentScript.getAttribute('src');
  27. }
  28. }
  29. module.exports = getCurrentScriptSource;