Javascript location href host

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: host property

The host property of the Location interface is a string containing the host, that is the hostname, and then, if the port of the URL is nonempty, a ‘:’ , and the port of the URL.

Value

Examples

const anchor = document.createElement("a"); anchor.href = "https://developer.mozilla.org/en-US/Location.host"; console.log(anchor.host === "developer.mozilla.org"); anchor.href = "https://developer.mozilla.org:443/en-US/Location.host"; console.log(anchor.host === "developer.mozilla.org"); // The port number is not included because 443 is the scheme's default port anchor.href = "https://developer.mozilla.org:4097/en-US/Location.host"; console.log(anchor.host === "developer.mozilla.org:4097"); 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

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

Your blueprint for a better internet.

Источник

Шпаргалка по window.location

https://voiti-v-it.com/posts/76?filter=JS#2 window.location.origin → ‘https://voiti-v-it.com’ .protocol → ‘https:’ .host → ‘voiti-v-it.com’ .hostname → ‘voiti-v-it.com’ .port → » .pathname → ‘posts/76’ .search → ‘?filter=JS’ .hash → ‘#2’ .href → ‘https://voiti-v-it.com/posts/76?filter=JS#2’ window.location.assign(‘url’) .replace(‘url’) .reload() .toString()

window.location .origin Базовый URL (Протокол + имя хоста + номер порта) .protocol Протокол (http: или https) .host Доменное имя + порт .hostname Доменное имя .port Имя порта .pathname Строка пути (относительно хоста) .search Часть строки, которая следует после? (включая ?) .hash Часть строки, которая следует после # (якорь или идентификатор фрагмента) .href Полный URL

В моем примере выше ты заметишь, что

возвращают одно и то же значение. Так в чем же разница. Ну, это связано с номером порта. Давай взглянем.

https://voiti-v-it.com window.location.host; // ‘voiti-v-it.com’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // »

http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’

будет содержать номер порта, тогда как

будет возвращать только имя хоста.

Ты можешь не только вызвать свойства объекта

чтобы получить информацию об URL. Ты можешь использовать его для установки новых свойств и изменения URL. Посмотрим, что я имею в виду.

http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’

Вот полный список свойств, которые ты можешь изменить:

http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’

Единственное свойство, которое ты не можешь установить, это

Это свойство доступно только для чтения.

который дает тебе информацию о текущем местоположении страницы. Ты также можешь получить доступ к объекту Location несколькими способами.

http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’

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

Каждый из 4х свойств выше указывают на один и тот же объект

и на самом деле не буду использовать

Главным образом потому, что

читается больше как общий термин, и кто-то может случайно назвать свою переменную, которая переопределяет глобальную переменную. Взять, к примеру:

Я думаю, что большинство разработчиков знают, что

является глобальной переменной. Так что у тебя меньше шансов вызвать путаницу. Поэтому я рекомендую использовать

Вот мой личный порядок предпочтений:

// ✅ 1. window.location // 🏆 2. document.location // ❌ 3. window.document.location // почему бы просто не использовать #1 or #2 😅 4. location // чувствуется слишком двусмысленно 😵

Конечно, это всего лишь мои предпочтения. Ты эксперт в своей кодовой базе, лучшего способа нет, лучший всегда тот, который подходит тебе и твоей команде.🤓

window.location .assign() Навигация происходит по указанному URL .replace() Навигация происходит по указанному URL & и текущая страница удаляется из истории .reload() Перезагружает текущую страницу .toString() Returns the URL

window.location.toString

Этот метод возвращает USVString URL. Версия только для чтения

Другими словами, ты можешь использовать его для получения значения

// https://voiti-v-it.com window.location.href; // https://voiti-v-it.com window.location.toString(); // https://voiti-v-it.com

Что касается использования, я не смог найти много информации о том, что лучше; но если ты это сделаешь, пожалуйста, поделись в комментах 😊. Я нашел тест производительности на разницу.

Один момент, который я хочу отметить в отношении этих тестов скорости, заключается в том, что они зависят от браузера. Различные браузеры и версии будут иметь разные результаты. Я использую Chrome, поэтому href вышел быстрее остальных. Так что я буду этим пользоваться. Также я думаю, что он читается более явно, чем

предоставит URL, тогда как

выглядит как нечто, преобразуемое в строку.😅

Оба эти метода помогут тебе перейти по другому URL. Разница в том, что

сохранит твою текущую страницу в истории, поэтому твой пользователь может использовать кнопку «назад» для перехода к ней. Принимая во внимание метод

он не сохраняет его истории. Это немного смущает, да? Меня тоже. Давай пройдемся по примерам.

1. Открыть новую вкладку 2. Перейти https://voiti-v-it.com (текущая страница) 3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)` 4. Нажать «назад» 5. Вернемся на 👉 https://voiti-v-it.com

1. Открыть новую вкладку 2. Перейти https://voiti-v-it.com (текущая страница) 3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)` 4. Нажать «назад» 5. Вернемся на 👉 чистую страницу

Мне просто нужно подчеркнуть «текущая страница» в определении. Это страница прямо перед

1. Открыть новую вкладку 2. Перейти www.developer.mozilla.org 3. Перейти https://voiti-v-it.com 👈 это будет текущая страница 4. window.location.assign(‘https://www.w3schools.com’); // Перейдет к #3 4. window.location.replace(‘https://www.w3schools.com’); // Перейдет к #2

Теперь ты знаешь, что мы можем изменить свойства

присвоив значение с помощью

Точно так же существуют методы, к которым мы можем получить доступ для выполнения некоторых действий. Итак, что касается «как перенаправить/редиректить на другую страницу», то есть 3 способа.

// Установить свойство href window.location.href = ‘https://voiti-v-it.com’; // Использование Assign window.location.assign(‘https://voiti-v-it.com’); // Использование Replace window.location.replace(‘https://voiti-v-it.com’);

replace vs assign vs href

Все три перенаправляют, разница связана с историей браузера.

здесь одинаковы. Они сохранят твою текущую страницу в истории, а

— нет. Так что, если ты предпочитаешь опыт создания, когда навигация не может вернуться на исходную страницу, используй

Таким образом, вопрос сейчас:

Я считаю, что это личные предпочтения. Мне больше нравится

потому что это метод, поэтому мне кажется, что я выполняю какое-то действие. Также есть дополнительный бонус в том, что его проще тестировать. Я писал много Jest-тестов, поэтому, используя метод можно просто замокать данные.

window.location.assign = jest.fn(); myUrlUpdateFunction(); expect(window.location.assign).toBeCalledWith(‘http://my.url’);

Но для тех, которые болеют за

для редиректа страницы. Я нашел тест производительности и он работает в моей версии Chrome быстрее. Опять же, тесты производительности варьируются в зависимости от браузера и разных версий, сейчас это может быть быстрее, но, возможно, в будущих браузерах всё может измениться.

Как это все появилось 👍

Ладно, я готов с вами поделиться как появилась эта шпаргалка. Я гуглил, как редиректить на другую страницу, и столкнулся с объектом

Иногда я чувствую, что разработчик является журналистом или детективом — для того, чтобы собрать всю доступную информацию, приходится много копаться и прочесывать разные источники. Честно говоря, я был ошеломлен материалами, они все были “о разном”, а я просто хотел всё из одного источника. Я не мог найти много полной информации, поэтому я подумал, а расскажу-ка я об этом в шпаргалке!

Ещё больше полезного в наших соц. сетях instagram, facebook, telegram

Источник

Читайте также:  Span style background color html
Оцените статью