Search code examples
javascriptrelative-pathweb-component

Get the path to the current JS web component


I have a JS web component that needs to load in other resources (specifically a src for an iframe it adds to the DOM, but this would be a problem for any resource with a relative path).

This resource needs to be specified relative to the calling page, which I can get easily enough from window.location.

However, the file that it needs to point the src at is relative to the JS file that's executing, and as that's a component I can't be sure where it will be.

So:

example.com/index.html 
  |__> {unknown path}/web-component.js
  |__> {unknown path}/resource.html <-- I want to get this

That component might be in node_modules or bower_components or webpackOutput or wherever, but the DOM it creates needs to point to the same location that it has been served from, not the page that's executing it.

As this code is in a web component document.currentScript is null and document.getElementsByTagName('script') might not include the component.


Solution

  • I have a potential solution, but it has both potential browser compatibility and performance issues.

    The idea is new Error().stack includes the path to the file executing.

    So...

    // Get stack string
    const stack = new Error().stack.split('at');
    
    // Get the last entry
    const scriptPath = stack[stack.length - 1].trim();
    
    // The component will share the path up to the last slash
    const componentPath = scriptPath.substring(0, scriptPath.lastIndexOf('/'));
    

    It relies on the format of the stack, the contents of the stack, and new Error() not causing any performance issues as it loads, so answers with a better method are welcome!