Get Url For Currently Executing Javascript

情到浓时终转凉″ 提交于 2019-12-14 02:20:09

问题


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.


回答1:


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:




回答2:


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.




回答3:


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) .




回答4:


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



来源:https://stackoverflow.com/questions/2203079/get-url-for-currently-executing-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!