Last Updated: February 25, 2016
·
375
· mattsirocki

JavaScript

The following code, if placed in a JavaScript file, will determine the path to the file.

// Determine Script Root
var tags = document.getElementsByTagName('script');
var tag  = tags[tags.length - 1]
var root = tag.src.split('?')[0].split('/').slice(0, -1).join('/');

How It Works

When a JavaScript file is executed, a script tag, containing the path to the file in the src attribute, must have been added to the DOM. By getting a list of all the script tags, we can get the tag which corresponds to the current file as long as the current file hasn't added any other script tags to the DOM.

From there, it's just a simple matter of massaging the value of the src attribute to remove the file name.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside