}

Javascript: How to set/get current URL?

Created:

Introduction

Using javascript, how to get the current active URL?

We are going to give an example to load the current URL and store its value in a variable. Then we will explain how how to change the current url using javascript.

Getting the current browser URL

The following code will store the current browser URL into the variable currentURL.

var currentURL = window.location.href;

You could have some issues with Firefox, try to use document.URL if you have some issues. Remember that document.URL is read-only, which should contain the same value as window.location.href. You can change the value of window.location.href to change the current URL.

Location useful properties like

Location object has a lot of useful properties like:

  • location.protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL)).
  • hostname: Host name specifies the host that owns the resource.
  • port: A port number used by the server
  • pathname: The path gives info about the specific resource within the host that the Web client wants to access.
  • query: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose.
  • hash: The anchor portion of a URL, includes the hash sign (#).

All these properties can be changed and they will be reflected on the browser.