get name and path of js file

Last post 11-19-2008 9:57 AM by gibble. 2 replies.

Sort Posts:

  • get name and path of js file

    11-18-2008, 4:47 PM
    • Participant
      786 point Participant
    • gibble
    • Member since 05-15-2007, 12:40 PM
    • Posts 226

    Is there a way to get the current filename and url of the running js file?

    Meaning, if I'm in browsing http://somedomain.com/pages/bar.html and include http://somedomain.com/js/foo.js can I have js in the foo.js file that tells me that it's http://somedomain.com/js/foo.js ?

  • Re: get name and path of js file

    11-18-2008, 9:00 PM
    Answer
    • All-Star
      20,656 point All-Star
    • A1ien51
    • Member since 05-06-2005, 6:46 PM
    • MD USA
    • Posts 3,794

    You can look at script tags in the page and look at the source, but you can not tell what file you are in directly.

    Eric

  • Re: get name and path of js file

    11-19-2008, 9:57 AM
    Answer
    • Participant
      786 point Participant
    • gibble
    • Member since 05-15-2007, 12:40 PM
    • Posts 226

    I actually found this trick yesterday minutes after posting, and it seems to be working quite well.  At the top of the js file you include the following code and since it's run as the DOM is being built, the last <script> tag in the document has to be the one you are in.  Thus:

            var scripts = document.getElementsByTagName('script');
            var script = scripts[scripts.length - 1];
            var pathWithFile = script.getAttribute("src");
            var path = pathWithFile.indexOf('/') >= 0
                ? pathWithFile.match(/^(.+)\//)[0]
                : '';

     It's working quite well.  

Page 1 of 1 (3 items)