Javascript узнать текущий url

window . location

location — это объект хранящийся в window , который позволяет получать информацию о текущем адресе страницы и менять его с помощью функций или обновления полей объекта.

Пример

Скопировать ссылку «Пример» Скопировано

С помощью location мы можем получить текущий адрес:

 // если выполнить этот скрипт на текущей странице доки в консолиconsole.log(window.location.href)// 'https://doka.guide/js/window-location/' // если выполнить этот скрипт на текущей странице доки в консоли console.log(window.location.href) // 'https://doka.guide/js/window-location/'      

Обновление текущей страницы можно произвести с помощью reload ( ) . Этот метод делает то же самое, что и кнопка «Обновить» в браузере:

 window.location.reload() window.location.reload()      

С помощью replace ( ) можно сделать клиентский редирект, это приведёт к мгновенному переходу по адресу, указанному при вызове метода:

 window.location.replace('https://doka.guide/') window.location.replace('https://doka.guide/')      

Как понять

Скопировать ссылку «Как понять» Скопировано

Для навигации по сайту мы используем адреса и параметры страницы. window . location содержит набор свойств и методов, чтобы удобно получать адрес и управлять им.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Свойства

Скопировать ссылку «Свойства» Скопировано

Ссылка, на которой обозначены все свойства window.location

href – полное представление адреса. Можно сказать, что это зеркало того, что находится в адресной строке браузера в данный момент. Если записать значение в это свойство, то произойдёт обновление адреса и редирект на новый адрес.

Остальные свойства — это кусочки location . href . Они нужны, чтобы удобно получать каждый из них отдельно, а не вытаскивать их руками из полной строки адреса.

 console.log(window.location.href)// отобразит текущий адресwindow.location.href = 'https://example.com'// сделает переход по указанному адресу console.log(window.location.href) // отобразит текущий адрес window.location.href = 'https://example.com' // сделает переход по указанному адресу      

protocol содержит текущий протокол по которому открыта страница. Чаще всего там будет https и http .

host содержит значение хоста из ссылки. Хост включает в себя название текущего домена и порта.

hostname — частичка с доменом из свойства host , не включает в себя порт.

port — вторая составляющая значения host , содержит только номер порта. Если порт не указан в явном виде, то значением свойства будет пустая строка » .

origin включает в себя путь, начиная с protocol и заканчивая port .

search содержит параметры в формате ключ = значение разделённые & . Если параметров нет, то значением будет пустая строка.

hash — якорная ссылка включая символ # . Она находится в самом конце пути и отвечает за навигацию между размеченными на странице элементами с помощью установки атрибута id на тегах. Эта часть URL не передаётся на сервер. Если параметров нет, то значением будет пустая строка.

 window.location.hash = 'в-работе'// проскролит страницу до элемента с `id="в-работе"` если такой присутствует на страницеconsole.log(window.location.hash)// напечатает якорь window.location.hash = 'в-работе' // проскролит страницу до элемента с `id="в-работе"` если такой присутствует на странице console.log(window.location.hash) // напечатает якорь      

pathname – репрезентация текущего пути на сайте. Если текущий урл не содержит путь, то значением будет корневой путь » / » .

Например, значения window . location . pathname в зависимости от адреса:

  • https : / / doka . guide / js / window — location / → /js / window — location / .
  • https : / / doka . guide → / .

Методы

Скопировать ссылку «Методы» Скопировано

assign ( новый _ путь ) – метод вызывает переход на страницу, переданную в аргументах. После перехода на страницу пользователь может вернуться на страницу, с которой произошёл переход, с помощью браузерной кнопки назад.

replace ( новый _ путь ) аналогичен методу assign ( ) , но адрес страницы с которой был вызван этот метод не будет сохранён в истории браузера. При попытке вернуться назад пользователь будет отправлен на страницу предшествующую той, с которой произошёл переход.

reload ( ) перезагружает текущую страницу.

to String ( ) приводит адрес страницы к строке. Возвращает то же самое значение, что и location . href .

Источник

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.

Источник

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);

Результат:

Источник

Читайте также:  Как построить график плотности python
Оцените статью