- Обновить страницу с помощью JS / HTML / PHP
- Цикличное обновление страницы с задержкой
- Перезагрузка страницы с задержкой
- Пример:
- Перезагрузка страницы с подтверждением
- Пример:
- Обновление родительской страницы из IFrame
- Перезагрузка страницы с помощью HTML
- Перезагрузка страницы из PHP
- Refresh the Page in JavaScript – JS Reload Window Tutorial
- Here’s an Interactive Scrim about How to Refesh the Page in JavaScript
- How to Refresh a Page in JavaScript With location.reload()
- How to Perform Page Reload/Refresh in JavaScript When a Button is Clicked
- How to Refresh/Reload a Page Automatically in JavaScript
- How to Refresh/Reload a Page Using the History Function in JavaScript
- Wrapping Up
- window . location
- Пример
- Как понять
- Как пишется
- Свойства
- Методы
- Window location.reload()
- Syntax
- Parameters
- Return Value
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Обновить страницу с помощью JS / HTML / PHP
JS -метод location.reload() перезагружает текущую вкладку браузера и действует также как кнопка «Обновить страницу».
Пример перезагрузки страницы кликом на ссылку или кнопку:
Цикличное обновление страницы с задержкой
В коде используется тот же location.reload() выполняемый с задержкой setTimeout() в тридцать секунд.
Перезагрузка страницы с задержкой
В случаях когда после клика на кнопку или ссылку нужно перезагрузить страницу с задержкой, например две секунды:
Обновить страницу через 2 секунды
Пример:
Перезагрузка страницы с подтверждением
Чтобы пользователь мог подтвердить действие, можно применить метод вызова диалогового сообщения confirm.
if (confirm('Вы действительно хотите обновить страницу?'))
Пример:
Обновление родительской страницы из IFrame
Для обращения к ресурсам родительской страницы из IFrame используется объект parent , подробнее в статье «Как обновить iframe».
Перезагрузка страницы с помощью HTML
Добавление мета-тега в страницы заставит её перезагрузится. Значение атрибута content больше нуля задает задержку в секундах.
Перезагрузка страницы из PHP
Обновить страницу прямо с сервера можно c помощью функции header() , отправив заголовок « Refresh: 5 », где значение «5» указывает интервал в пять секунд.
Важно, чтобы перед вызовом функции не было отправки контента в браузер, например echo .
Refresh the Page in JavaScript – JS Reload Window Tutorial
Joel Olawanle
When you’re developing applications like a blog or a page where the data may change based on user actions, you’ll want that page to refresh frequently.
When the page refreshes or reloads, it will show any new data based off those user interactions. Good news – you can implement this type of functionality in JavaScript with a single line of code.
In this article, we will learn how to reload a webpage in JavaScript, as well as see some other situations where we might want to implement these reloads and how to do so.
Here’s an Interactive Scrim about How to Refesh the Page in JavaScript
How to Refresh a Page in JavaScript With location.reload()
You can use the location.reload() JavaScript method to reload the current URL. This method functions similarly to the browser’s Refresh button.
The reload() method is the main method responsible for page reloading. On the other hand, location is an interface that represents the actual location (URL) of the object it is linked to – in this case the URL of the page we want to reload. It can be accessed via either document.location or window.location .
The following is the syntax for reloading a page:
Note: When you read through some resources on “page reload in JavaScript”, you’ll come across various explanations stating that the relaod method takes in boolean values as parameters and that the location.reload(true) helps force-reload so as to bypass its cache. But this isn’t the case.
According to the MDN Documentation, a boolean parameter is not part of the current specification for location.reload() — and in fact has never been part of any specification for location.reload() ever published.
Browsers such as Firefox, on the other hand, support the use of a non-standard boolean parameter known as forceGet for location.reload() , which instructs Firefox to bypass its cache and force-reload the current document.
Aside from Firefox, any parameters you specify in a location.reload() call in other browsers will be ignored and have no effect.
How to Perform Page Reload/Refresh in JavaScript When a Button is Clicked
So far we have seen how reload works in JavaScript. Now let’s now see how you can implement this could when an event occurs or when an action like a button click occurs:
Note: This works similarly to when we use document.location.reload() .
How to Refresh/Reload a Page Automatically in JavaScript
We can also allow a page refersh after a fixed time use the setTimeOut() method as seen below:
Using the code above our web page will reload every 3 seconds.
So far, we’ve seen how to use the reload method in our HTML file when we attach it to specific events, as well as in our JavaScript file.
How to Refresh/Reload a Page Using the History Function in JavaScript
The History function is another method for refreshing a page. The history function is used as usual to navigate back or forward by passing in either a positive or negative value.
For example, if we want to go back in time, we will use:
This will load the page and take us to the previous page we navigated to. But if we only want to refresh the current page, we can do so by not passing any parameters or by passing 0 (a neutral value):
Note: This also works the same way as we added the reload() method to the setTimeOut() method and the click event in HTML.
Wrapping Up
In this article, we learned how to refresh a page using JavaScript. We also clarified a common misconception that leads to people passing boolean parameters into the reload() method.
Embark on a journey of learning! Browse 200+ expert articles on web development. Check out my blog for more captivating content from me.
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 содержит набор свойств и методов, чтобы удобно получать адрес и управлять им.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
Свойства
Скопировать ссылку «Свойства» Скопировано
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 .
Window location.reload()
The reload() method does the same as the reload button in your browser.
Syntax
Parameters
Return Value
Browser Support
location.reload() is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
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.