Obtain the URL for the JavaScript code that is currently running

Can anyone help me find the URL of the JavaScript currently being executed? I am aware of using window.location.href for the current page, but that doesn't necessarily provide the path to the script that is running.

Any assistance would be greatly appreciated.

Thank you.

EDIT 1: I am open to utilizing plugins or other methods to achieve this. Please feel free to suggest any solutions.

EDIT 2: I need to determine the relative path from my executing script to another resource. The challenge arises when the script is located at /js/myScript.js and the resource I need to reference is at /imgs/test.png. Due to the script being included from various locations, the path to the .png file remains unknown.

Answer №1

Give this a shot, although I can't guarantee it will function correctly on all web browsers. It worked fine on my Firefox:

var scripts = document.getElementsByTagName("SCRIPT");
var script  = scripts[scripts.length-1].src;

var scriptName = script.match(/[^\\|^\/]+\.\w+\w?$/);
alert(scriptName);

This code snippet will display the name of the script file in an alert message.

Answer №2

After coming across a similar inquiry on Stack Overflow regarding equivalence in JavaScript, I found the solution provided by Kamarey to be very helpful.

Here is what Kamarey suggested:

Utilize the base tag:

<head> 
   <base href="http://www.example.com/myapp/" /> 
</head> 

...

Now, any links used on this page, whether in JavaScript or HTML, will be relative to the base tag, which is "http://www.example.com/myapp/".

Although it wasn't exactly what I had in mind, setting the base resolved the root issue I was facing. By defining the base, all requests are made in relation to that specification.

UPDATE: It seems that the jQuery method getScript() does not adhere to the base location in Firefox 3.5.7. This could possibly be an issue specific to Firefox rather than jQuery. While everything works fine in IE8, I have raised a ticket with jQuery to explore potential improvements in behavior. You can follow the progress at .

Answer №3

It doesn't seem possible to achieve this using JavaScript alone. You may require a JavaScript tracing plug-in.

UPDATE: Tools like Firebug and the IE8 debugger (press F12) can assist you in accomplishing this task.

Answer №4

One clever trick is to leverage browser errors and implement a try/catch block to uncover the exact file location.

I've come up with a straightforward function. Check it out here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the process of retrieving an element by its ID when dealing with dynamically generated IDs in AngularJS

I am creating a list using the following code snippet: <div ng-repeat="list in fileUploadList"> <div id="{{list}}Upload"></div> </div> Within the controller, I need to retrieve the element by ID, so I am utilizing this line of ...

Sending an array of dictionary objects to a JavaScript function

I have a situation where I need to pass a large amount of data stored in an NSArray containing NSDictionary objects to a JavaScript function using a webview and the method: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script My inquir ...

What is the proper way to retrieve the app object from a module in ExpressJS?

In my application, I am running an Express app by setting it up in the app.js file: var app = express(); Once the app is created, I can define variables like this: app.set('host', 'myhost') Now, within my project, I also have a sepa ...

Can you please tell me the event that is triggered when an option is unselected in Vue.Drag

I am trying to figure out the event for selecting an item since I already know about the "choose" event. However, I am uncertain about what to use for un-selecting an item. In my particular case, I am unable to utilize the @end event. <draggable :list= ...

Tips for chaining actions in Javascript using ActionSequence, LegacyActionSequence, or a similar method

I encountered an error while attempting to execute this example, despite trying both ActionSequence and LegacyActionSequence. I am in search of the correct method to chain actions. My attempts to find a solution in resources such as https://seleniumhq.git ...

A nifty little JavaScript tool

Recently, I created a bookmarklet that opens a new window with a specified URL and passes variables to a PHP script using the GET method. However, I now require it to load the same PHP script and pass the same variables but within a div element this time. ...

Stopping unauthorized users from manipulating REST URLs

I am currently exploring methods to prevent an exploit where a user manipulates the URL, specifically in a GET request scenario. The following code represents a route on my Express router that processes incoming requests for a certain collection "A" and re ...

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Connecting to an Oracle database using Alfresco's Javascript API may seem daunting at first, but

Currently, I am working on a project that involves using Alfresco. One of the new requirements for this project is to retrieve a sequence number from our Oracle database and populate a custom property within an Alfresco space. var conObj = new ActiveXObje ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

Leverage ajax/js to dynamically refresh a single select tag within a set of multiple

While working on a project, I encountered a challenge while using JavaScript to update a <select> tag within a page. The specific issue arises because the page is designed in a management style with multiple forms generated dynamically through PHP ba ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

Having trouble updating text in a PDF using NodeJS and hummus library

How can NodeJS be used to replace a string in a PDF file? offers a solution for text replacement in a PDF document. However, when applying the same code, an issue arises where the replaced text is visible in the source code of the PDF but does not render p ...

Steps for sending a form with jQuery's submit method1. Start

Below is the jquery code that I have written: $(document).ready(function () { $('.bar_dropdown').on('change', function() { console.log("dropdown changed") $('#bar_graph_form_id').submit(function(e ...

php After the ajax request, the array_push function is failing to add values to the

I am having trouble with my ajax and php implementation. I want to append an array every time an ajax call is made, but it doesn't seem to be working. Here are the codes I am using: $('#multiple_upload_form' +count).ajaxForm({ ...

Encountering a series of errors in Discord.js v14 while executing a specific

UPDATE :- After troubleshooting, I discovered that the previous error stemmed from my command handler itself! However, now I am encountering a whole bunch of new errors... actually, multiple errors. So, I'm in desperate need of assistance. (Note: Apol ...

Stopping a Bootstrap Modal Closure When Validation Errors are Present

I'm dealing with a bootstrap model within a .NET MVC5 app. Although my client-side validation is functioning properly (using jquery unobtrusive in MVC), I have encountered an issue where the modal keeps closing even when there are errors present. How ...

Having trouble with Isomorphic fetch not functioning properly for external requests?

EDIT: I am trying to determine why the response does not include the requested data and whether it is due to missing libraries or the format of my fetchUrl variable. Hello, I am attempting to utilize the isomorphic fetch method for making AJAX requests bu ...

Having Trouble Retrieving Environment Variables in Next.js API Endpoints

Currently, I am in the process of working on a project utilizing Next.js 13 and API routes to communicate with a database. My goal is to securely store my database credentials in a .env file, but unfortunately, the variables are not loading as expected. I ...

Transform every key and value into an array

How can I separate each key and value into individual arrays? Here is the current data: var inputArray = { "3/10/2017": 52, "3/11/2017": 58, "3/12/2017": 70, "3/13/2017": 76 } The desired output should be: var outputArray = [ ["3/10/2017", 52 ...