So I am writing a jquery Plugin using grunt, and in my plugin I also need to call webservices.
The webservice url domain will always be the same domain as the location of the .js file the user needs to add for our plugin. So i.e. Relative
1) Include JS file for plugin
http://mydomain1/js/myfile.js
2) In my JS call API URL
Needs to be
api_domain: "http://mydomain1/api/v1"
And I want the api domain to be relative to domain of the JS file calling it I tried doing
api_domain: "/mydomain1/api/v1"
But this picks up the domain name of the browser.
So I was wondering what the best way to achieve this
1) Use a .NET Handler to insert the right domain name from context.request.url
2) In Grunt build create a specific .js for each environment I will deploy to which has the full url in the JS
3) Other Options ?
Well you could actually have the script find it's own source using jquery. Just make sure to give the js file a unique enough name.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/demux/4d4ce440d7c379305a9a/raw/findfilehosttest.js"></script>
Actual Script:
$(function(){
var url = $("script[src$='findfilehosttest.js']").attr('src')
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i)
var domain = matches && matches[1]
alert(domain)
})
But in general I think it's best to keep it simple. So allow the user to set the URL of the server manually, like so:
<script>
var MY_API_URL = 'https://instance1.myapiserver.foo'
</script>
<script src="/whateverpath/myapiscript.js"></script>
This would also allow them to host the script on their own server, or even proxy it for what ever reason they might have.
Will your JS file be on the same domain as the web page? In that case, simply use window.location.host
in your plugin to get "http://mydomain".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With