JavaScript Introduction | Browser Object Model | Location Object
Location Object
The location object can be used to get the address of the HTML document currently displayed in the browser or to load a new document in the browser.
This object is connected both to the location property of the Window object and to the location property of the Document object. By using the properties and methods of the location object, you can parse and process the current document’s URL address in various ways.
URL Address of the Current Document
The href property of the location object returns the full URL address of the current document as a string.
document.write("The address of the current document is " + location.href + ".");
Host Name of the Current Document
The hostname property of the location object returns the Internet host name of the current document.
document.write("The host name of the current document is " + location.hostname + ".");
Major properties of the location object, such as host, hostname, port, and hash, store various characteristics of a URL address. These properties are also provided through the Link object.
File Path Name of the Current Document
The pathname property of the location object returns the file path name of the current document.
document.write("The file path name of the current document is " + location.pathname + ".");
The combination of a host name and path name is called a URL, or Uniform Resource Locator. A URL is a convention that tells the browser where the requested content is located when it requests content from a web server.
Loading a Document in the Current Window
The assign() method of the location object loads the document at the specified URL address in the browser window. The replace() method differs from assign() in that it removes the current document from the browser’s history before loading the new document. The reload() method of the location object reloads the current document in the browser window.
function openDocument() {
location.assign("/index.php");
}
function openDocumentWithReplace() {
location.replace("/index.php");
}
Removing the current document from the browser’s history means that even if the browser’s Back button is pressed, the user cannot return to the previous page.