Reputation: 4110
I'm trying to find the url for the currently executing javascript. I know I can use window.location.href
for the current page, but that's not necessarily the path to the script which is executing.
Any help is greatly appreciated.
Thanks.
EDIT 1: I'm fully open to the use of plugins and such to accomplish this. Don't hesitate to suggest anything.
EDIT 2: I need this so that I can find a relative path from where my currently executing script is at to another resource. The issue is that, for example, the script is running at /js/myScript.js and the resource I need to reference is at /imgs/test.png. Since the .js file can be included from anywhere, the path to the .png file cannot be known.
Upvotes: 2
Views: 1263
Reputation: 2476
You can take advantage of errors produced by browsers and use a try/catch to find out the absolute file location.
I've coded a simple function. You can see it here
Upvotes: 0
Reputation: 4110
Based on a similar question at ~/ equivalent in javascript, the answer by Kamarey solved my problem.
From the answer by Kamarey:
Use base tag:
<head> <base href="http://www.example.com/myapp/" /> </head>
...
from now any link use on this page, no matter in javascript or html, will be relative to the base tag, which is "http://www.example.com/myapp/".
Obviously this isn't exactly what I was looking for but it solved the underlying problem I was having. By specifying the base, all requests are made relative to the base specification.
EDIT: For anyone interested, it appears as though the jQuery method getScript() does not respect the base location in Firefox 3.5.7. Obviously this may not be an actual bug in jQuery and could be more of a Firefox issue but it's worth noting. In IE8 everything seems to work appropriately. I've filed a ticket with jQuery to see if maybe they can streamline the behavior. You can track it at http://dev.jquery.com/ticket/6034.
Upvotes: 2
Reputation: 114417
I don't think you can do this with JavaScript. You'd need a JavaScript trace plug-in.
EDIT: Firebug can help you with this, as can the IE8 debugger (press F-12) .
Upvotes: 0
Reputation: 32918
Try this but i cant guarantee that it will work with all browsers in my firefox it worked:
var scripts = document.getElementsByTagName("SCRIPT");
var script = scripts[scripts.length-1].src;
var scriptName = script.match(/[^\\|^\/]+\.\w+\w?$/);
alert(scriptName);
Will alert the script name:
Upvotes: 2