I spent a lot of time searching for jQuery code snippet that could fetch the current url path from where the jQuery file is executed. But jQuery method

$(location).attr('protocol') + "//" + $(location).attr('host');

fetches the url of the current page. But to fetch the url of the path from where the Javascript is executed, is not possible with pure jQuery method unless you use some jQuery plugin or write your own function. Let us take an example, my Javascript file is executed from here – http://somedomain/folder/script.js, but when I use the above jQuery method the url returned will be http://somedomain. But I need the url path http://somedomain/folder, the actual location from where the jQuery or Javascript is executed.

In case of php it is lot easier to get the current directory from where the php script is executed. Also jQuery is executed at the client side, that is in the browser window, so no way to get the path of the Javascript file from the server. So I wrote my own function with jQuery, here it is.

function urlofdoc ( jsfile ) {
var scriptElements = document.getElementsByTagName('script');
var i, element, myfile;
for( i = 0; element = scriptElements[i]; i++ ) {
myfile = element.src;
if( myfile.indexOf( jsfile ) >= 0 ) {
var myurl = myfile.substring( 0, myfile.indexOf( jsfile ) );
}
}
return myurl;
}

A bit of explanation – Our function urlofdoc ( jsfile ) takes the file name as argument, so lets us call the function like this

var myurl = urlofdoc ( "script.js" );

getElementsByTagName will fetch all the script tags and store it in an array, which will contain the whole string from opening script tag to close tag

script path in jquery

after that every element source is checked for the occurrence of our file.

if( myfile.indexOf( jsfile ) >= 0 ) {
var myurl = myfile.substring( 0, myfile.indexOf( jsfile ) );
}

if the file is found, then we trim the filename using substring from the full url and return the path, in our example if we call the urlofdoc function with script.js as argument, it will return http://somedomain/folder.

Get the path of executed Javascript file
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *