Узнать адрес страницы javascript

Location

The Location interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the Document and Window interface have such a linked Location , accessible via Document.location and Window.location respectively.

Location anatomy

Hover over the URL segments below to highlight their meaning:

span id="href" title="href" >span id="origin" title="origin" >span id="protocol" title="protocol">https:span>//span id="host" title="host" >span id="hostname" title="hostname">example.orgspan>:span id="port" title="port" >8080span >span >span >span id="pathname" title="pathname">/foo/barspan >span id="search" title="search">?q=bazspan >span id="hash" title="hash">#bangspan>span > 
html  display: table; width: 100%; > body  display: table-cell; text-align: center; vertical-align: middle; font-family: Georgia; font-size: 175%; line-height: 1em; white-space: nowrap; > [title]  position: relative; display: inline-block; box-sizing: border-box; line-height: 2em; cursor: pointer; color: gray; > [title]::before  content: attr(title); font-family: monospace; position: absolute; top: 100%; width: 100%; left: 50%; margin-left: -50%; font-size: 60%; line-height: 1.5; background: black; > [title]:hover::before, :target::before  background: black; color: yellow; > [title] [title]::before  margin-top: 1.5em; > [title] [title] [title]::before  margin-top: 3em; > [title] [title] [title] [title]::before  margin-top: 4.5em; > [title]:hover, :target  position: relative; z-index: 1; outline: 50em solid rgba(255, 255, 255, 0.8); > 
.body.addEventListener("click", (event) =>  event.preventDefault(); window.location.hash = event.target.hasAttribute("id") ? `#$event.target.getAttribute("id")>` : ""; >); 

Instance properties

A static DOMStringList containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given Location object.

A stringifier that returns a string containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.

A string containing the protocol scheme of the URL, including the final ‘:’ .

A string containing the host, that is the hostname, a ‘:’ , and the port of the URL.

A string containing the domain of the URL.

A string containing the port number of the URL.

A string containing an initial ‘/’ followed by the path of the URL, not including the query string or fragment.

A string containing a ‘?’ followed by the parameters or «querystring» of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring.

A string containing a ‘#’ followed by the fragment identifier of the URL.

Returns a string containing the canonical form of the origin of the specific location.

Instance methods

Loads the resource at the URL provided in parameter.

Reloads the current URL, like the Refresh button.

Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the assign() method and setting the href property is that after using replace() the current page will not be saved in session History , meaning the user won’t be able to use the back button to navigate to it.

Returns a string containing the whole URL. It is a synonym for Location.href , though it can’t be used to modify the value.

Examples

// location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container const loc = document.location; console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container console.log(loc.protocol); // https: console.log(loc.host); // developer.mozilla.org:8080 console.log(loc.hostname); // developer.mozilla.org console.log(loc.port); // 8080 console.log(loc.pathname); // /en-US/search console.log(loc.search); // ?q=URL console.log(loc.hash); // #search-results-close-container console.log(loc.origin); // https://developer.mozilla.org:8080 location.assign("http://another.site"); // load another page 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 6, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Location – URL текущей страницы

Объект Location связан с адресной строкой браузера, в его свойствах содержатся все компоненты URL доступные для чтения и записи.

Доступ к Location обычно осуществляется через объекты Document.location или Window.location . Если скрипт запускается из iframe (в одном домене), доступ к родительскому окну доступен через window.parent.location .

Рассмотрим какие будут значения при следующим URL:

Location.href

Вернет полный URL страницы.

console.log(window.location.href);

Результат:

http://www.example.com/pages/contats?page=1&sort=2#marker

Объекту location можно присвоить новый URL, браузер сразу перейдет на новую страницу.

window.location.href = 'https//snipp.ru';

Так же для редиректа можно использовать методы location.assign() и location.replace() . Отличие последнего в том, что пользователь не сможет использовать кнопку «назад».

window.location.assign('https//snipp.ru');
window.location.replace('https//snipp.ru');

Location.protocol

Возвращает используемый протокол, включая : .

console.log(window.location.protocol);

Результат:

Location.port

Номер порта, если его нет в URL, то ни чего не выведется.

console.log(window.location.port);

Location.host

Содержит домен и порт (если есть).

console.log(window.location.host);

Результат:

Источник

How to Get the Current URL with JavaScript – JS Location Tutorial

Joel Olawanle

Joel Olawanle

How to Get the Current URL with JavaScript – JS Location Tutorial

If you’re a web developer, you’ll work with JavaScript when building dynamic and interactive web applications. One common task that you’ll need to perform is getting the current URL of a web page.

In this article, you will learn how to get the current URL using JavaScript’s Location object. I’ll show you some examples alongside some best practices.

How to Use the Location Object

The Location object is a built-in JavaScript object that provides information about the current URL of a web page. It contains various properties allowing you to access and modify different parts of a URL.

To access the Location object, you can use the window.location property. This returns the Location object for the current web page. This object contains many data, such as the URL, pathname, origin, host, search data, and more.

< "ancestorOrigins": < "0": "https://codepen.io" >, "href": "https://cdpn.io/cpe/boomboom/index.html?editors=0012&key=index.html-f1981af8-7dc2-f8b6-669a-8980d4a8d02a", "origin": "https://cdpn.io", "protocol": "https:", "host": "cdpn.io", "hostname": "cdpn.io", "port": "", "pathname": "/cpe/boomboom/index.html", "search": "?editors=0012&key=index.html-f1981af8-7dc2-f8b6-669a-8980d4a8d02a", "hash": "" > 

How to Access the Current URL With JavaScript

One common use case for the Location object is to get the current URL of a web page. You can do this by accessing the href property of the Location object.

The href property contains the complete URL of the current web page:

const currentUrl = window.location.href; console.log(currentUrl); 

This will log the current URL of the web page to the console.

How to Parse the Current URL With JavaScript

In addition to getting the current URL, you may need to parse it to extract specific parts. For example, you may want to extract the protocol, host, or path from the URL.

To parse the current URL, you can use the various properties of the Location object. For example, you can use the protocol property to get the protocol of the current URL:

const protocol = window.location.protocol; console.log(protocol); 

This will log the protocol of the current URL (for example, «http:» or «https:») to the console.

Other properties of the Location object that you can use to extract parts of the current URL include host , hostname , port , pathname , search , and hash .

const host = window.location.host; const pathname = window.location.pathname; const search = window.location.search; const hash = window.location.hash; 

Using these properties, you can extract various parts of the current URL.

How to Update the Current URL With JavaScript

In addition to getting and parsing the current URL, you may need to update it. For example, you may need to redirect the user to a different URL or modify the current URL dynamically.

To update the current URL, you can use the various methods of the Location object. For example, you can use the replace() method to replace the current URL with a new URL:

const newUrl = "https://example.com/new-page.html"; window.location.replace(newUrl); 

This will replace the current URL with the new one, redirecting the user to the new page.

Best Practices When Working With the Location Object

When working with the Location object, there are some best practices that you should follow to avoid potential pitfalls. For example, you should always check if the Location object is available before using it.

You should also be careful when modifying the current URL, as it can affect the user’s browsing experience. For example, you should avoid modifying the URL’s protocol, host, or port unless absolutely necessary.

Conclusion

In this article, you have learned how to get the current URL of a web page using JavaScript’s Location object. By understanding how to work with the Location object, you can build more dynamic and interactive web applications that provide a better user experience.

Thank you for reading, and I hope you have found this article informative and helpful. You can read this article on how to refresh a page with JavaScript for more information on working with URLs in JavaScript.

If you would like to learn more about JavaScript and web development, Browse 200+ expert articles on web development written by me, and also check out my blog for more captivating content.

Источник

Читайте также:  Различия html и javascript
Оцените статью