32

How do I get the base URL using javascript?

E.g., When I browse my site from visual studio, and if my URL is http://localhost:20201/home/index, I would want to get http://localhost:20201

If I host my site on IIS, and if my virtual directory name is MyApp and the URL is http://localhost/MyApp/home/index, I would want to get http://localhost/MyApp

I tried using location.protocol + location.hostname (and location.host), they work fine when i browse my site via visual studio, but when I host it on IIS, I get http://localhost, the /MyApp is truncated off.

Null Reference
  • 11,260
  • 40
  • 107
  • 184

8 Answers8

42

You should avoid doing such detection in JavaScript and instead pass the value from the .NET code. You will always risk running into problems with urls like http://server/MyApp/MyApp/action where you cannot know which is the name of a controller and which the path to the application.

In your Layout.cshtml file (or wherever you need it) add the following code:

<script type="text/javascript">
    window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode(Url.Content("~/"), true));
    alert(window.applicationBaseUrl + "asd.html");

    // if you need to include host and port in the url, use this:
    window.applicationBaseUrl = @Html.Raw(HttpUtility.JavaScriptStringEncode(
        new Uri(
                   new Uri(this.Context.Request.Url.GetLeftPart(UriPartial.Authority)),
                   Url.Content("~/")
               ).ToString(), true));
    alert(window.applicationBaseUrl + "asd.html");
</script>

The new Uri() part is needed so that the URL is always combined correctly (without manually checking if each part starts or ends with / symbol).

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • if you need an absolute path (including the host and port, see my updated answer) – Knaģis May 22 '13 at 11:31
  • Tried this on hosted IIS application, it shows `http://localhost` without /MyApp. I do not want to hardcode the "/MyApp" part – Null Reference May 22 '13 at 11:35
  • works for me :) what is the output for just `Url.Content("~/asd.html")` in .NET code? `Url.Content()` is a built-in method that resolves the `/MyApp` part. – Knaģis May 22 '13 at 11:41
  • This solution is predicated on the assumption that it runs within a Razor view Re: the @Html.Raw() function. If you place this code outside of that Razor view, it will no longer work. – Spencer Sullivan Feb 19 '20 at 18:27
4

If you are using .NET Core, you can get url setting a JavaScript variable in a global scope (For example in Layout.cshtml File, this file is in the folder Views/Shared):

 <script type="text/javascript">
    var url = '@string.Format("{0}://{1}{2}", Context.Request.Scheme, Context.Request.Host.Value , Url.Content("~/"))';
</script>

From version C# 6 with interpolation:

<script type="text/javascript">
    var url = '@($"{Context.Request.Scheme}://{Context.Request.Host.Value}{Url.Content("~/")}")';
</script>
Scaduto
  • 66
  • 5
3
var url = window.location.href.split('/');
var baseUrl = url[0] + '//' + url[2];
vijay
  • 1,323
  • 1
  • 11
  • 15
1

Try the below code.

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}



document.write(getBaseURL());

Thanks,

Siva

SivaRajini
  • 7,225
  • 21
  • 81
  • 128
1

I don't think that this is possible as the JavaScript (the Client) doesn't know anything about your deployment (MyApp) and treats it as part of the pathinfo (just like /home/index). As a workaround you could try to interpret the pathinfo (location.pathname) according to the domain or port.

But you could set a JavaScript variable in a global scope (or what ever suits you) containing the path (the path is generated by the server and placed into the variable).

This could look something like that in your html-Head:

<script type="text/javascript">
    var global_baseurl = '<insert server side code that gets the path depending on your server side programming language>';
</script>
Werzi2001
  • 2,035
  • 1
  • 18
  • 41
1

I think a clean solution will be like

Putting the base URL in the _layout Html like so

<div id="BaseUrl" data-baseurl="@Context.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")"></div>    

Context.Request.Url.GetLeftPart(UriPartial.Authority) will give you in

local http://localhost:20201 from IIS will give you http://localhost

Url.Content("~/") in the local will be empty but in IIS will give you the app name, in your case MyApp

Then from the Js:

var baseUrl = $("#BaseUrl").data("baseurl");

Than you can Use it Like:

$.getJSON(baseUrl + "/Home/GetSomething", function (data) {
      //Do something with the data
});

https://msdn.microsoft.com/en-us/library/system.uri.getleftpart(v=vs.110).aspx http://api.jquery.com/data/

HB MAAM
  • 3,913
  • 4
  • 29
  • 39
0

You can set a base url in the head tag of your page. All links/hrefs will use this to call relatieve hrefs.

@{ var baseHref = new System.UriBuilder(Request.Url.AbsoluteUri) { Path = Url.Content("~/") }; }
<base href="@baseHref" />

Explanation:

  • Url.Content("~/") returns the relative path (in this case MyApp on the server)
  • new System.UriBuilder(Request.Url.AbsoluteUri) creates an UriBuilder that contains port and protocol information
E. Mourits
  • 295
  • 2
  • 11
0
var base_url = "@Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")"

Define it in layout file and append base_url. This worked for me.

Prince Prasad
  • 1,528
  • 1
  • 16
  • 20