Using JavaScript to retrieve URL information
<script type="text/javascript">
document.write("location.host=" + location.host + "<br>");
document.write("location.hostname=" + location.hostname + "<br>");
document.write("location.href=" + location.href + "<br>");
document.write("location.pathname=" + location.pathname + "<br>");
document.write("location.protocol=" + location.protocol + "<br>");
</script>
Executing the JavaScript code to retrieve URL information produces the following result:
Details on Using window.location to Get URL Information
A Uniform Resource Locator (URL) consists of several parts:
scheme://host:port/path?query#fragment
scheme: Communication protocol
Common examples include http, ftp, and mailto.
host: Host
The domain name or IP address of the server.
port: Port number
An integer, optional; if omitted, the default port for the scheme is used, such as port 80 for http.
path: Path
A string separated by one or more "/" symbols, typically representing a directory or file address on the host.
query: Query
Optional, used to pass parameters to dynamic web pages (such as those created with CGI, ISAPI, PHP/JSP/ASP/ASP.NET, etc.), with multiple parameters separated by "&", and each parameter's name and value separated by "=" symbol.
framgent: Fragment
A string used to specify a fragment of a network resource. For example, if a webpage has multiple definitions, a fragment can directly point to a specific definition (also known as an anchor).
Example:
1, window.location.href
The entire URL string (the complete address bar in the browser)
Return value: http://www.2astudio.com:80/view.asp?id=209#cmt1323
2, window.location.protocol
The protocol part of the URL
Return value: http:
3, window.location.host
The host part of the URL
Return value: www.2astudio.com
4, window.location.port
The port part of the URL. If the default port 80 is used (update: evenif :80 is added), the return value is not the default 80 but an empty string.
In this case, the return value is: empty
5, window.location.pathname
The path part of the URL (the file address)
Return value: /view.asp
6, window.location.search
The query (parameter) part. In addition to passing values to dynamic languages, it can also be used with static pages and JavaScript to obtain corresponding parameter values.
Return value: ?id=209
7, window.location.hash
Anchor point
Return value: #cmt1323
- document.referrer
Retrieves the link of the previous page.