Categories: Uncategorized

How to Get the current URL with JavaScript

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

Code

<p id="demooo"></p>

<script>
document.getElementById("demooo").innerHTML = 
"The full URL of this page is:<br>" + window.location.href;
</script>

JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser’s address bar. All these methods use the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows:

var currentLocation = window.location;

Basic URL Structure

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. For example, www.stackoverflow.com. A server provides services using the name of the host.

port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.

pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example, /index.html.

search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).

hash: The anchor portion of a URL, includes the hash sign (#).

With these Location object properties you can access all of these URL components and what they can set or return:

href - the entire URL
protocol - the protocol of the URL
host - the hostname and port of the URL
hostname - the hostname of the URL
port - the port number the server uses for the URL
pathname - the path name of the URL
search - the query portion of the URL
hash - the anchor portion of the URL
reecry

Recent Posts

Insta360 – Videos keep exporting backwards | Wrong side render in insta360

https://youtu.be/0RRUOIvmuWA I realized that I had my camera set up incorrectly, so when I upload…

9 months ago

Make Animated progress step bar using Figma

https://youtu.be/C3oFfV20K_c Make Animated progress step bar using Figma

11 months ago

How to Hide All Grids in Figma

https://youtu.be/o3pSH_oRzko How to Hide All Grids in Figma

11 months ago

How to Create Responsive Tool tip in figma

https://youtu.be/hdSUylKSsho How to Create Responsive Tool tip in Figma

11 months ago

Pixel Grid not visible in figma | How to Turn on figma Pixel Grid

https://youtu.be/AEiH7dSDhKo Having issue in figma pixel grid? learn how to show/ hide figma pixel grid…

11 months ago

Fix External Monitor Lag on Mac OS Ventura

https://youtu.be/iilYzHg9LwQ There are some issues going on in ventura OS its still in development phase…

2 years ago