How to refresh a page using JavaScript
Overview
In JavaScript, we can refresh a page using the following methods:
location.reload()history.go(0)
The location.reload() method
This method reloads the current URL, like the browser's refresh button.
Syntax
window.location.reload();
Parameters
This method does not accept any parameter.
Return values
This method does not return any value.
Example
Let's see an example of the location.reload() method in the code snippet below:
const btn = document.getElementById('btn')
// attach event listener on btn
btn.addEventListener('click', () => {
// reload the page
window.location.reload()
})Explanation
In the index.html file,
Line 6: We create a button with
id="btn".
In the index.js file,
Line 1: We use the
getElementById()method to find the element withid="btn".Line 4: We attach the
clickevent listener to the button.Line 6: We refresh the page using
location.reload()when the button is clicked.
2. The history.go(0) method
This method uses the History object of the browser to reload a URL, depending on the value of the specified parameter.
Syntax
history.go(number);
Parameters
number: This specifies the position to which we want to move with respect to the current URL. Anegativevalue will move backward in history, whereas apositivevalue will move forward. If no parameter is passed or if the value is0, this method will reload the current URL.
Return values
This method does not return any value.
Example
Let's see an example of the history.go() method in the code snippet below:
const btn = document.getElementById('btn')
// attach event listener on btn
btn.addEventListener('click', () => {
// reload the page
history.go(0);
})Explanation
In the index.html file,
Line 6: We create a button with
id="btn".
In the index.js file,
Line 1: We use the
getElementById()method to find the element withid="btn".Line 4: We attach the
clickevent listener to the button.Line 6: We refresh the page using
history.go()when the button is clicked.
Besides these methods, we can also refresh the page by reassigning a value to the current URL, as shown below:
// re-assigning the value of current locationwindow.location = window.location// for URL with POST requestwindow.location = window.location.pathname