In a webpage URL, the protocol (i.e. http: or https:) is the standard that specifies how data is transferred and transmitted amongst computers.

When working with JavaScript, how do you get the URL protocol of the current page?

Luckily, JavaScript has a built-in way for you to do this using its Location API interface, which represents the location (URL) of the current webpage you're located on. The global Window interface has access to the Location object that can be used via window.location.

Here's what the method looks like in practice:

    
      window.location.protocol
    
  

This will return a USVString representing the protocol scheme of the current page's URL with the : included.

And here are some examples of what values it can return:

    
      // "http:"
      // "https:"
      // "file:"
      // "ftp:"
      // "mailto:"
    
  

For more information on the browser support for this method, see its MDN web docs page.

Thanks for reading and happy coding!