Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Getting Current Location Details

The JavaScript location object provides an easy way to get various pieces of information about the URL the user is currently viewing. Because JavaScript and jQuery code are often used across multiple pages, the location object is the means to get information about what URL the browser is currently viewing. The following sections provide some phrases that provide information about the browser’s current location.

Finding the Current Hash

The location.hash value returns the current hash, if any, that the browser is using. This is useful when you are displaying a web page with multiple hash anchors. The hash provides a context to the location on the page the user actually clicked.

Getting the Host Name

The location.hostname value returns the domain name of the server that sent the page to the user. This is just the portion after the protocol but before the port number or path. This allows you to determine which server to send AJAX requests back to. Often, multiple servers may handle the web site, but you may want to interact only with the server that served the web page in the first place.

Looking at the File Path

The location.pathname returns the path that the page was loaded from on the server. The pathname also provides a context as to what page the user is looking at.

Getting the Query String

The location.search value returns the query string that was passed to the server to load the page. Typically, you think about a query string as a server-side script tool. However, it can be just as valuable to JavaScript code that manipulates the data returned from the server and requests additional information from the server via AJAX.

Determining If the Page Is Viewed on a Secure Protocol

The easiest way to determine if a page is being viewed from a secured location on the server is to look at the location.protocol value. This value will be http on regular requests or https on secure requests.

  • + Share This
  • 🔖 Save To Your Account