0

Hi currently I am working on a jQuery plugin in which I make an API call. Rather than hard coding the URL for the API, I would like it to be relative in terms of the URL of the JS file of the plugin

So say I have the following set up

Page loading the file

http://mydomain1.com

In that page I load

<script src="http://mydomain2.com/Scripts/myPlugin.min.js">

In that JS file, I load the API url as

api_endpoint: "/myApi/api/v1",

I was hoping this would resolve to

http://mydomain2.com/myApi/api/v1

but it resolves to

http://mydomain1.com/myApi/api/v1

Is there anyway in Javascript I can set the domainname relative to the JS File loading the script rather than the page itself ?

1 Answer 1

5

As per my understanding of your problem, you want url of your external file as a base URL. So you can use below code to access that:

  1. Captured all the script files of the document
  2. Defined index to get the script file and refined any query string from the url
  3. Now used split and slice to remove last directory name(folder name) and join to make complete url

...

var scriptTags = document.getElementsByTagName('script');
var filterPath = scriptTags[0].src.split('?')[0];      // Hopping your script is on first place of dom and removing any ?query
var scriptFilePathUrl = filterPath.split('/').slice(0, -1).join('/');
alert(scriptFilePathUrl);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.