Html script window location

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.

Источник

JavaScript Window Location

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

Window Location

The window.location object can be written without the window prefix.

  • window.location.href returns the href (URL) of the current page
  • window.location.hostname returns the domain name of the web host
  • window.location.pathname returns the path and filename of the current page
  • window.location.protocol returns the web protocol used (http: or https:)
  • window.location.assign() loads a new document

Window Location Href

The window.location.href property returns the URL of the current page.

Example

Display the href (URL) of the current page:

Window Location Hostname

The window.location.hostname property returns the name of the internet host (of the current page).

Example

Display the name of the host:

Window Location Pathname

The window.location.pathname property returns the pathname of the current page.

Example

Display the path name of the current URL:

Window Location Protocol

The window.location.protocol property returns the web protocol of the page.

Example

Window Location Port

The window.location.port property returns the number of the internet host port (of the current page).

Example

Display the name of the host:

Most browsers will not display default port numbers (80 for http and 443 for https)

Window Location Assign

The window.location.assign() method loads a new document.

Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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 .

Источник

Читайте также:  Http spo ipc39 ru login index php
Оцените статью