Location Object Properties and Methods

In JavaScript, the BOM (Browser Object Model) refers to a collection of objects provided by the browser for managing browser windows and documents. Among them, the location object is an object within the BOM that provides information about the current page's URL and operations related to it.

The location object contains numerous properties and methods that can be used to retrieve or modify the URL information of the current page. Below are some commonly used properties and methods of the location object:

  • location.href: Returns or sets the complete URL of the current page.
  • location.protocol: Returns or sets the protocol portion of the current page, such as "http:" or "https:".
  • location.host: Returns or sets the hostname and port number portion of the current page, for example "www.example.com:8080".
  • location.hostname: Returns or sets the hostname portion of the current page, for example "www.example.com".
  • location.port: Returns or sets the port number portion of the current page, for example "8080".
  • location.pathname: Returns or sets the path portion of the current page, for example "/path/to/file.html".
  • location.search: Returns or sets the query string portion of the current page, for example "?key=value".
  • location.hash: Returns or sets the anchor portion of the current page, for example "#section1".
  • location.reload(): Used to reload the current page.

It is important to note that due to browser security restrictions, JavaScript can only modify certain properties of the URL on the current page, such as location.hash, location.search, and others; it cannot be used to modify other parts.

In addition to the above properties and methods, the location object provides other attributes and methods, such as location.assign(), location.replace(), location.toString(), etc.