I have the following code that changes the pages from within JavaScript:
var newUrl = [some code to build up URL string];
window.location.replace(newUrl);
But it doesn’t change the top URL, so when someone clicks the back button it doesn’t go back to the previous page.
How can I have JavaScript change the top URL as well so the browser back button works.
Pikamander2
6,8643 gold badges46 silver badges66 bronze badges
asked Oct 2, 2010 at 18:08
answered Oct 2, 2010 at 18:10
glebmglebm
19.8k8 gold badges51 silver badges67 bronze badges
0
Simple assigning to window.location
or window.location.href
should be fine:
window.location = newUrl;
However, your new URL will cause the browser to load the new page, but it sounds like you’d like to modify the URL without leaving the current page. You have two options for this:
-
Use the URL hash. For example, you can go from
example.com
toexample.com#foo
without loading a new page. You can simply setwindow.location.hash
to make this easy. Then, you should listen to the HTML5hashchange
event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers. -
You could use HTML5 History to modify the path without reloading the page. This will allow you to change from
example.com/foo
toexample.com/bar
. Using this is easy:window.history.pushState("example.com/foo");
When the user presses «back», you’ll receive the window’s
popstate
event, which you can easily listen to (jQuery):$(window).bind("popstate", function(e) { alert("location changed"); });
Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.
answered Oct 2, 2010 at 18:34
bcherrybcherry
7,1122 gold badges28 silver badges37 bronze badges
3
If you just want to update the relative path you can also do
window.location.pathname = '/relative-link'
"http://domain.com" -> "http://domain.com/relative-link"
answered Aug 2, 2016 at 19:23
ArtokunArtokun
5335 silver badges9 bronze badges
Hmm, I would use
window.location = 'http://localhost/index.html#?options=go_here';
I’m not exactly sure if that is what you mean.
answered Oct 2, 2010 at 18:11
BlenderBlender
285k52 gold badges432 silver badges490 bronze badges
This will do it:
window.history.pushState(null,null,'https://www.google.com');
answered Feb 11, 2021 at 17:05
<script>
var url= "http://www.google.com";
window.location = url;
</script>
answered Sep 17, 2019 at 10:24
The best way to redirect the user to another URL is by using window.location.assign
(See https://developer.mozilla.org/en-US/docs/Web/API/Location/assign).
Nevertheless, if what you want is to change the URL of the page without redirecting the user, then you may use the window.history.replaceState
function (See https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState). A combination of this and window.history.pushState
is what Single Page Applications (SPAs) use nowadays to keep track of the user navigating throughout the application so that the back button works as expected
You can take a look at the examples in the documentation links I provided to give you an idea on the usage of these functions
answered Jan 9 at 19:47
How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
asked Sep 25, 2008 at 22:00
Steven NobleSteven Noble
10k13 gold badges45 silver badges57 bronze badges
5
If you want it to work in browsers that don’t support history.pushState
and history.popState
yet, the «old» way is to set the fragment identifier, which won’t cause a page reload.
The basic idea is to set the window.location.hash
property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don’t support onhashchange
(IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval
for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you’re using jQuery there’s a hashchange plugin that will use whichever method the browser supports. I’m sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
answered Sep 25, 2008 at 22:08
Matthew CrumleyMatthew Crumley
101k24 gold badges107 silver badges129 bronze badges
7
With HTML 5, use the history.pushState
function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState
instead.
7
window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.
answered Sep 25, 2008 at 22:19
1
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches…
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
answered Sep 25, 2008 at 22:07
Paul DixonPaul Dixon
293k51 gold badges310 silver badges344 bronze badges
5
jQuery has a great plugin for changing browsers’ URL, called jQuery-pusher.
JavaScript pushState
and jQuery could be used together, like:
history.pushState(null, null, $(this).attr('href'));
Example:
$('a').click(function (event) {
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
});
Using only JavaScript history.pushState()
, which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.
Example:
window.history.pushState("object", "Your New Title", "/new-url");
The pushState() method:
pushState()
takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let’s examine each of these three parameters in more detail:
-
state object — The state object is a JavaScript object which is associated with the new history entry created by
pushState()
. Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry’s state object.The state object can be anything that can be serialized. Because Firefox saves state objects to the user’s disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to
pushState()
, the method will throw an exception. If you need more space than this, you’re encouraged to use sessionStorage and/or localStorage. -
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you’re moving.
-
URL — The new history entry’s URL is given by this parameter. Note that the browser won’t attempt to load this URL after a call to
pushState()
, but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it’s relative, it’s resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise,pushState()
will throw an exception. This parameter is optional; if it isn’t specified, it’s set to the document’s current URL.
answered Oct 8, 2013 at 21:04
IliaIlia
12.9k11 gold badges52 silver badges85 bronze badges
Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.
Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).
When doing this I’ll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.
I hope that sets you on the right path.
answered Sep 25, 2008 at 22:11
Jethro LarsonJethro Larson
2,3181 gold badge24 silver badges24 bronze badges
2
Facebook’s photo gallery does this using a #hash in the URL. Here are some example URLs:
Before clicking ‘next’:
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
After clicking ‘next’:
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
Note the hash-bang (#!) immediately followed by the new URL.
answered Jan 11, 2011 at 15:43
Jonathon HillJonathon Hill
3,4161 gold badge33 silver badges31 bronze badges
A more simple answer i present,
window.history.pushState(null, null, "/abc")
this will add /abc
after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to «https://stackoverflow.com/abc»
answered Feb 15, 2019 at 18:19
samsam
1,7471 gold badge24 silver badges44 bronze badges
What is working for me is — history.replaceState()
function which is as follows —
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
answered Apr 26, 2018 at 6:52
Veshraj JoshiVeshraj Joshi
3,4742 gold badges26 silver badges44 bronze badges
I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.
So like let’s say the user is at the page: http://domain.com/site/page.html
Then the browser can let me do location.append = new.html
and the page becomes: http://domain.com/site/page.htmlnew.html
and the browser does not change it.
Or just allow the person to change get parameter, so let’s location.get = me=1&page=1
.
So original page becomes http://domain.com/site/page.html?me=1&page=1
and it does not refresh.
The problem with # is that the data is not cached (at least I don’t think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.
From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div
is used to handle different method overtime, that data is not stored for each history state.
Drew Noakes
295k162 gold badges671 silver badges736 bronze badges
answered Mar 31, 2009 at 20:33
user58670user58670
1,43817 silver badges17 bronze badges
my code is:
//change address bar
function setLocation(curLoc){
try {
history.pushState(null, null, curLoc);
return false;
} catch(e) {}
location.hash = '#' + curLoc;
}
and action:
setLocation('http://example.com/your-url-here');
and example
$(document).ready(function(){
$('nav li a').on('click', function(){
if($(this).hasClass('active')) {
} else {
setLocation($(this).attr('href'));
}
return false;
});
});
That’s all
answered Oct 29, 2013 at 18:07
Tusko TrushTusko Trush
4223 silver badges15 bronze badges
0
I’ve had success with:
location.hash="myValue";
It just adds #myValue
to the current URL. If you need to trigger an event on page Load, you can use the same location.hash
to check for the relevant value. Just remember to remove the #
from the value returned by location.hash
e.g.
var articleId = window.location.hash.replace("#","");
answered Jun 23, 2014 at 11:56
Adam HeyAdam Hey
1,4161 gold badge20 silver badges22 bronze badges
How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
asked Sep 25, 2008 at 22:00
Steven NobleSteven Noble
10k13 gold badges45 silver badges57 bronze badges
5
If you want it to work in browsers that don’t support history.pushState
and history.popState
yet, the «old» way is to set the fragment identifier, which won’t cause a page reload.
The basic idea is to set the window.location.hash
property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don’t support onhashchange
(IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval
for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you’re using jQuery there’s a hashchange plugin that will use whichever method the browser supports. I’m sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
answered Sep 25, 2008 at 22:08
Matthew CrumleyMatthew Crumley
101k24 gold badges107 silver badges129 bronze badges
7
With HTML 5, use the history.pushState
function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState
instead.
7
window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.
answered Sep 25, 2008 at 22:19
1
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches…
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
answered Sep 25, 2008 at 22:07
Paul DixonPaul Dixon
293k51 gold badges310 silver badges344 bronze badges
5
jQuery has a great plugin for changing browsers’ URL, called jQuery-pusher.
JavaScript pushState
and jQuery could be used together, like:
history.pushState(null, null, $(this).attr('href'));
Example:
$('a').click(function (event) {
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
});
Using only JavaScript history.pushState()
, which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.
Example:
window.history.pushState("object", "Your New Title", "/new-url");
The pushState() method:
pushState()
takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let’s examine each of these three parameters in more detail:
-
state object — The state object is a JavaScript object which is associated with the new history entry created by
pushState()
. Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry’s state object.The state object can be anything that can be serialized. Because Firefox saves state objects to the user’s disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to
pushState()
, the method will throw an exception. If you need more space than this, you’re encouraged to use sessionStorage and/or localStorage. -
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you’re moving.
-
URL — The new history entry’s URL is given by this parameter. Note that the browser won’t attempt to load this URL after a call to
pushState()
, but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it’s relative, it’s resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise,pushState()
will throw an exception. This parameter is optional; if it isn’t specified, it’s set to the document’s current URL.
answered Oct 8, 2013 at 21:04
IliaIlia
12.9k11 gold badges52 silver badges85 bronze badges
Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.
Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).
When doing this I’ll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.
I hope that sets you on the right path.
answered Sep 25, 2008 at 22:11
Jethro LarsonJethro Larson
2,3181 gold badge24 silver badges24 bronze badges
2
Facebook’s photo gallery does this using a #hash in the URL. Here are some example URLs:
Before clicking ‘next’:
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
After clicking ‘next’:
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
Note the hash-bang (#!) immediately followed by the new URL.
answered Jan 11, 2011 at 15:43
Jonathon HillJonathon Hill
3,4161 gold badge33 silver badges31 bronze badges
A more simple answer i present,
window.history.pushState(null, null, "/abc")
this will add /abc
after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to «https://stackoverflow.com/abc»
answered Feb 15, 2019 at 18:19
samsam
1,7471 gold badge24 silver badges44 bronze badges
What is working for me is — history.replaceState()
function which is as follows —
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
answered Apr 26, 2018 at 6:52
Veshraj JoshiVeshraj Joshi
3,4742 gold badges26 silver badges44 bronze badges
I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.
So like let’s say the user is at the page: http://domain.com/site/page.html
Then the browser can let me do location.append = new.html
and the page becomes: http://domain.com/site/page.htmlnew.html
and the browser does not change it.
Or just allow the person to change get parameter, so let’s location.get = me=1&page=1
.
So original page becomes http://domain.com/site/page.html?me=1&page=1
and it does not refresh.
The problem with # is that the data is not cached (at least I don’t think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.
From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div
is used to handle different method overtime, that data is not stored for each history state.
Drew Noakes
295k162 gold badges671 silver badges736 bronze badges
answered Mar 31, 2009 at 20:33
user58670user58670
1,43817 silver badges17 bronze badges
my code is:
//change address bar
function setLocation(curLoc){
try {
history.pushState(null, null, curLoc);
return false;
} catch(e) {}
location.hash = '#' + curLoc;
}
and action:
setLocation('http://example.com/your-url-here');
and example
$(document).ready(function(){
$('nav li a').on('click', function(){
if($(this).hasClass('active')) {
} else {
setLocation($(this).attr('href'));
}
return false;
});
});
That’s all
answered Oct 29, 2013 at 18:07
Tusko TrushTusko Trush
4223 silver badges15 bronze badges
0
I’ve had success with:
location.hash="myValue";
It just adds #myValue
to the current URL. If you need to trigger an event on page Load, you can use the same location.hash
to check for the relevant value. Just remember to remove the #
from the value returned by location.hash
e.g.
var articleId = window.location.hash.replace("#","");
answered Jun 23, 2014 at 11:56
Adam HeyAdam Hey
1,4161 gold badge20 silver badges22 bronze badges
In this quick article, we’ll discuss how to change the URL in JavaScript by redirecting. We’ll go through a couple of different methods that you can use to perform JavaScript redirects.
JavaScript is one of the core technologies of the web. The majority of websites use it, and all modern web browsers support it without the need for plugins. In this series, we’re discussing different tips and tricks that might help you in your day-to-day JavaScript development.
When you’re working with JavaScript, you often need to redirect users to a different page. JavaScript provides different ways of doing that.
Today, we’ll discuss how to perform URL redirections in vanilla JavaScript and with the jQuery library.
How to Change the URL in Vanilla JavaScript
In this section, we’ll go through the different built-in methods provided by JavaScript to implement URL redirection. In fact, JavaScript provides the location
object, a part of the window object, which allows you to perform different URL-related operations.
The location.href
Method
The location.href
method is one of the most popular ways to perform JavaScript redirects. If you try to get the value of location.href
, it returns the value of the current URL. Similarly, you can also use it to set a new URL, and users will then be redirected to that URL.
Let’s go through the following example.
1 |
console.log(location.href); |
2 |
// prints the current URL
|
3 |
|
4 |
location.href = 'https://code.tutsplus.com'; |
5 |
// redirects the user to https://code.tutsplus.com
|
As you can see, it’s fairly easy to redirect users with the location.href
method. Since the location
object is part of the window
object, the above snippet can also be written as:
1 |
window.location.href = 'https://code.tutsplus.com'; |
So in this way, you can use the location.href
method to change the URL and redirect users to a different webpage.
The location.assign
Method
The location.assign
method works very similarly to the location.href
method and allows you to redirect users to a different web page.
Let’s quickly see how it works with the following example.
1 |
location.assign('https://code.tutsplus.com'); |
As you can see, it’s pretty straightforward. You just need to pass the URL in the first argument of the assign
method, and it will redirect users to that URL. It’s important to note that the assign
method maintains the state of the History
object. We’ll discuss this in detail in the next section.
The location.replace
Method
You can also use the location.replace
method to perform JavaScript redirects. The location.replace
method allows you to replace the current URL with a different URL to perform redirection.
Let’s see how it works with the following example.
1 |
location.replace('https://code.tutsplus.com'); |
Although the location.replace
method looks very similar to the location.href
and location.assign
methods of redirecting users to a different URL, there’s an important difference between them. When you use the location.replace
method, the current page won’t be saved in the session, and it’s actually removed from the JavaScript History
object. So users won’t be able to use the back button to navigate to it.
Let’s try to understand it with the following example.
1 |
// let’s assume that a user is browsing https://code.tutsplus.com
|
2 |
|
3 |
// a user is redirected to a different page with the location.href method
|
4 |
location.href = 'https://design.tutsplus.com'; |
5 |
|
6 |
// a user is redirected to a different page with the location.replace method
|
7 |
location.replace('https://business.tutsplus.com'); |
In the above example, we’ve assumed that a user is browsing the https://code.tutsplus.com
webpage. Next, we have used the location.href
method to redirect the user to the https://design.tutsplus.com
webpage. Finally, we’ve used the location.replace
method to redirect the user to the https://business.tutsplus.com
webpage. Now, if the user clicks on the back button, it would go back to https://code.tutsplus.com
instead of https://design.tutsplus.com
, since we’ve used the location.replace
method, and it has actually replaced the current URL with https://business.tutsplus.com
in the History
object.
So you should understand the difference between location.replace
and other methods before you use them. You can’t use them interchangeably since the location.replace
method alters the state of the JavaScript History
object. And thus, if you want to preserve the state of the History
object, you should use other methods of redirecting users.
How to Perform URL Redirections With jQuery
Although vanilla JavaScript offers enough options when it comes to URL redirection, if you’re still wondering how to do it with the jQuery library, we’ll quickly go through it in this section.
In jQuery, you can use the attr
method to perform redirection, as shown in the following snippet.
1 |
$(location).attr('href', 'https://design.tutsplus.com'); |
As you can see, it’s fairly easy to redirect users with jQuery!
So that’s it for the different ways of performing JavaScript redirects. And with that, we’ve reached the end of this quick article as well.
Conclusion
Today, we discussed how you can implement JavaScript redirects. We discussed different methods that you can use to perform JavaScript redirects, along with some examples.
Did you find this post useful?
Software Engineer, FSPL, India
I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.
Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.
I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!
Ищешь данные URL сайта, тогда объект
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
window.location
.origin
Базовый URL (Протокол + имя хоста + номер порта)
.protocol
Протокол (http: или https)
.host
Доменное имя + порт
.hostname
Доменное имя
.port
Имя порта
.pathname
Строка пути (относительно хоста)
.search
Часть строки, которая следует после? (включая ?)
.hash
Часть строки, которая следует после # (якорь или идентификатор фрагмента)
.href
Полный URL
Разница между host и hostname
В моем примере выше ты заметишь, что
host
и
hostname
возвращают одно и то же значение. Так в чем же разница. Ну, это связано с номером порта. Давай взглянем.
URL без порта
https://voiti-v-it.com
window.location.host; // ‘voiti-v-it.com’
window.location.hostname; // ‘voiti-v-it.com’
window.location.port; // »
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’
Таким образом,
host
будет содержать номер порта, тогда как
hostname
будет возвращать только имя хоста.
Как изменить свойства URL
Ты можешь не только вызвать свойства объекта
location
чтобы получить информацию об 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’
Единственное свойство, которое ты не можешь установить, это
window.location.origin
Это свойство доступно только для чтения.
Объект Location
window.location
возвращает объект
Location
который дает тебе информацию о текущем местоположении страницы. Ты также можешь получить доступ к объекту 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’
Объект доступен таким образом, потому что является глобальной переменной в браузере.
window.location vs location
Каждый из 4х свойств выше указывают на один и тот же объект
Location
Я лично предпочитаю
window.location
и на самом деле не буду использовать
location
Главным образом потому, что
location
читается больше как общий термин, и кто-то может случайно назвать свою переменную, которая переопределяет глобальную переменную. Взять, к примеру:
// https://www.samanthaming.com
location.protocol; // ‘https’
function localFile() {
const location = ‘/sam’;
return location.protocol;
// ❌ undefined
// локальная «location» преопределяет глобальную переменную
}
Я думаю, что большинство разработчиков знают, что
window
является глобальной переменной. Так что у тебя меньше шансов вызвать путаницу. Поэтому я рекомендую использовать
window.location
вместо
location
Вот мой личный порядок предпочтений:
// ✅
1. window.location // 🏆
2. document.location
// ❌
3. window.document.location // почему бы просто не использовать #1 or #2 😅
4. location // чувствуется слишком двусмысленно 😵
Конечно, это всего лишь мои предпочтения. Ты эксперт в своей кодовой базе, лучшего способа нет, лучший всегда тот, который подходит тебе и твоей команде.🤓
Методы window.location
window.location
.assign()
Навигация происходит по указанному URL
.replace()
Навигация происходит по указанному URL & и текущая страница удаляется из истории
.reload()
Перезагружает текущую страницу
.toString()
Returns the URL
window.location.toString
Вот определение из MDN
Этот метод возвращает USVString URL. Версия только для чтения
Location.href
Другими словами, ты можешь использовать его для получения значения
href
из
// https://voiti-v-it.com
window.location.href; // https://voiti-v-it.com
window.location.toString(); // https://voiti-v-it.com
Что касается использования, я не смог найти много информации о том, что лучше; но если ты это сделаешь, пожалуйста, поделись в комментах 😊. Я нашел тест производительности на разницу.
Один момент, который я хочу отметить в отношении этих тестов скорости, заключается в том, что они зависят от браузера. Различные браузеры и версии будут иметь разные результаты. Я использую Chrome, поэтому href вышел быстрее остальных. Так что я буду этим пользоваться. Также я думаю, что он читается более явно, чем
toString()
Совершенно очевидно, что
href
предоставит URL, тогда как
toString
выглядит как нечто, преобразуемое в строку.😅
assign vs replace
Оба эти метода помогут тебе перейти по другому URL. Разница в том, что
assign
сохранит твою текущую страницу в истории, поэтому твой пользователь может использовать кнопку «назад» для перехода к ней. Принимая во внимание метод
replace
он не сохраняет его истории. Это немного смущает, да? Меня тоже. Давай пройдемся по примерам.
Assign
1. Открыть новую вкладку
2. Перейти https://voiti-v-it.com (текущая страница)
3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)`
4. Нажать «назад»
5. Вернемся на 👉 https://voiti-v-it.com
Replace
1. Открыть новую вкладку
2. Перейти https://voiti-v-it.com (текущая страница)
3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)`
4. Нажать «назад»
5. Вернемся на 👉 чистую страницу
Текущая страница
Мне просто нужно подчеркнуть «текущая страница» в определении. Это страница прямо перед
assign
или
replace
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
Как сделать редирект страницы
Теперь ты знаешь, что мы можем изменить свойства
window.location
присвоив значение с помощью
=
Точно так же существуют методы, к которым мы можем получить доступ для выполнения некоторых действий. Итак, что касается «как перенаправить/редиректить на другую страницу», то есть 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
Все три перенаправляют, разница связана с историей браузера.
href
и
assign
здесь одинаковы. Они сохранят твою текущую страницу в истории, а
replace
— нет. Так что, если ты предпочитаешь опыт создания, когда навигация не может вернуться на исходную страницу, используй
replace
Таким образом, вопрос сейчас:
href
vs
assign
Я считаю, что это личные предпочтения. Мне больше нравится
assign
потому что это метод, поэтому мне кажется, что я выполняю какое-то действие. Также есть дополнительный бонус в том, что его проще тестировать. Я писал много Jest-тестов, поэтому, используя метод можно просто замокать данные.
window.location.assign = jest.fn();
myUrlUpdateFunction();
expect(window.location.assign).toBeCalledWith(‘http://my.url’);
Но для тех, которые болеют за
href
для редиректа страницы. Я нашел тест производительности и он работает в моей версии Chrome быстрее. Опять же, тесты производительности варьируются в зависимости от браузера и разных версий, сейчас это может быть быстрее, но, возможно, в будущих браузерах всё может измениться.
Как это все появилось 👍
Ладно, я готов с вами поделиться как появилась эта шпаргалка. Я гуглил, как редиректить на другую страницу, и столкнулся с объектом
window.location
Иногда я чувствую, что разработчик является журналистом или детективом — для того, чтобы собрать всю доступную информацию, приходится много копаться и прочесывать разные источники. Честно говоря, я был ошеломлен материалами, они все были “о разном”, а я просто хотел всё из одного источника. Я не мог найти много полной информации, поэтому я подумал, а расскажу-ка я об этом в шпаргалке!
The Window.location
read-only property returns a
Location
object with information about the current location of the
document.
Though Window.location
is a read-only Location
object, you can also assign a string to it. This means that you can
work with location
as if it were a string in most cases:
location = 'http://www.example.com'
is a synonym of
location.href = 'http://www.example.com'
.
See Location
for all available properties.
Value
Examples
Basic Example
alert(location); // alerts "https://developer.mozilla.org/en-US/docs/Web/API/Window/location"
Example 1: Navigate to a new page
Whenever a new value is assigned to the location object, a document will be loaded
using the URL as if location.assign()
had been called with the modified
URL.
Note that navigation-related sandbox flags may result in an exception being thrown and the navigation failing.
location.assign("http://www.mozilla.org"); // or
location = "http://www.mozilla.org";
Example 2: Reloading the current page
Example 3
Consider the following example, which will reload the page by using the replace()
method to
insert the value of location.pathname
into the hash:
function reloadPageWithHash() {
location.replace(`http://example.com/#${location.pathname}`);
}
Example 4: Display the properties of the current URL in an alert dialog
function showLoc() {
const logLines = ["Property (Typeof): Value", `location (${typeof location}): ${location}`];
for (const prop in location) {
logLines.push(`${prop} (${typeof location[prop]}): ${location[prop] || "n/a"}`);
}
alert(logLines.join("n"));
}
// in html: <button onclick="showLoc();">Show location properties</button>
Example 5: Send a string of data to the server by modifying the search
property
function sendData(data) {
location.search = data;
}
// in html: <button onclick="sendData('Some data');">Send data</button>
The current URL with «?Some%20data» appended is sent to the server (if no action is
taken by the server, the current document is reloaded with the modified search string).
Example 6: Using bookmarks without changing the hash
property
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>MDN Example</title>
<script>
function showNode(node) {
document.documentElement.scrollTop = node.offsetTop;
document.documentElement.scrollLeft = node.offsetLeft;
}
function showBookmark(bookmark, useHash) {
if (arguments.length === 1 || useHash) {
location.hash = bookmark;
return;
}
const bookmarkElement = document.querySelector(bookmark);
if (bookmarkElement) {
showNode(bookmarkElement);
}
}
</script>
<style>
span.intLink {
cursor: pointer;
color: #0000ff;
text-decoration: underline;
}
</style>
</head>
<body>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices
dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus
auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in
placerat est. Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor.
Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris
vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla
consectetur aliquam purus. Curabitur convallis, justo posuere porta
egestas, velit erat ornare tortor, non viverra justo diam eget arcu.
Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit
a hendrerit vitae, volutpat non ipsum.
</p>
<p>
Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero,
eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt
rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida
nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat.
Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit.
Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non
felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et
fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla
mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent
bibendum condimentum feugiat.
</p>
<p id="myBookmark1">
[ <span class="intLink" onclick="showBookmark('#myBookmark2');"
>Go to bookmark #2</span
> ]
</p>
<p>
Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin
ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros
convallis ut mollis magna pellentesque. Pellentesque placerat enim at
lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt
tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas
mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.
</p>
<p>
Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc,
vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis.
Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem
ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc.
Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem
ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu
sem vehicula egestas.
</p>
<p>
Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus
sit amet lectus vitae eros egestas pellentesque fermentum eget magna.
Quisque mauris nisl, gravida vitae placerat et, condimentum id metus.
Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae
sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales
quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in
mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames
ac turpis egestas.
</p>
<p>
Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem
ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu
turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra.
Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae
molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci.
Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit,
turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio
ante.
</p>
<p>
Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit
amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum.
Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim
turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante
ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla
euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet
turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum,
diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut
nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.
</p>
<p>
Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper.
Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a
aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas,
ligula magna laoreet libero, eu commodo mauris odio id ante. In hac
habitasse platea dictumst. In pretium erat diam, nec consequat eros.
Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed
pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie
nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu
faucibus in. Curabitur id arcu est. In semper mollis lorem at
pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et
tortor. Pellentesque porttitor facilisis ultricies.
</p>
<p id="myBookmark2">
[ <span class="intLink" onclick="showBookmark('#myBookmark1');"
>Go to bookmark #1</span
>
|
<span class="intLink" onclick="showBookmark('#myBookmark1', false);"
>Go to bookmark #1 without using location.hash</span
>
|
<span class="intLink" onclick="showBookmark('#myBookmark3');"
>Go to bookmark #3</span
> ]
</p>
<p>
Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla
sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque
tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque
nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut
libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat
libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie.
Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id
sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus
rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis
lacinia rutrum ipsum varius.
</p>
<p>
Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum
sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare
aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis
et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis
ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices
augue, ac sodales sem mollis in.
</p>
<p id="myBookmark3"><em>Here is the bookmark #3</em></p>
<p>
Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et
turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim
enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis,
varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit
pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus.
Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat
nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed
vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor
arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat
malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna
velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas
nulla nisl, facilisis eu egestas scelerisque, mollis eget metus.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
cubilia Curae; Morbi sed congue mi.
</p>
<p>
Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi.
Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet
magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et
pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus
consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed
consectetur. Cum sociis natoque penatibus et magnis dis parturient montes,
nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis
convallis, bibendum vitae turpis.
</p>
<p>
Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie
sollicitudin felis a porta. Mauris nec orci sit amet orci blandit
tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan
fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien
ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget
tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non.
Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam
sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer
egestas leo eu turpis blandit scelerisque.
</p>
<p>
Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi
gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing
pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante
condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna,
porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus.
Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing
eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet.
Proin vel odio at lacus vehicula aliquet.
</p>
<p>
Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper
malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum
risus, eget consequat urna laoreet nec. Etiam mollis quam non sem
convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis
ligula mattis eget vestibulum diam hendrerit. In non placerat mauris.
Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea
dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis
vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat
volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa,
pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.
</p>
<p>
Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo
blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et
ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing
facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum
ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est
eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem
neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non
velit aliquam cursus. Integer semper condimentum tortor a pellentesque.
Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus,
vitae consequat augue urna vel odio.
</p>
<p>
Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed
nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit.
Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis
neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum
imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui
tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus
vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis
libero.
</p>
<p>
Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed
consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor
rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit,
ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis
in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem.
Nullam sollicitudin magna sed sem mollis id commodo libero condimentum.
Duis eu massa et lacus semper molestie ut adipiscing sem.
</p>
<p>
Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In
quis varius elit. Nullam dignissim neque nec velit vulputate porttitor.
Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar
quis condimentum ut, porta nec justo. In hac habitasse platea dictumst.
Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque
placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget
convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut
tristique lacus luctus quis.
</p>
<p>
Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed
facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu
sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum
aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices
tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc
fringilla eget. Praesent scelerisque urna vitae nibh tristique varius
consequat neque luctus. Integer ornare, erat a porta tempus, velit justo
fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel
dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar
laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque
sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales
eleifend interdum.
</p>
</body>
</html>
…the same thing but with an animated page scroll:
const showBookmark = (() => {
let _useHash;
let _scrollX;
let _scrollY;
let _nodeX;
let _nodeY;
let _itFrame;
let _scrollId = -1;
let _bookMark;
// duration: the duration in milliseconds of each frame
// frames: number of frames for each scroll
let duration = 200;
let frames = 10;
function _next() {
if (_itFrame > frames) {
clearInterval(_scrollId);
_scrollId = -1;
return;
}
_isBot = true;
document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / frames);
document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / frames);
if (_useHash && _itFrame === frames) {
location.hash = _bookMark;
}
_itFrame++;
}
function _chkOwner() {
if (_isBot) {
_isBot = false;
return;
}
if (_scrollId > -1) {
clearInterval(_scrollId);
_scrollId = -1;
}
}
window.addEventListener("scroll", _chkOwner, false);
return (bookmark, useHash) => {
const node = document.querySelector(bookmark);
_scrollY = document.documentElement.scrollTop;
_scrollX = document.documentElement.scrollLeft;
_bookMark = bookmark;
_useHash = useHash === true;
_nodeX = node.offsetLeft;
_nodeY = node.offsetTop;
_itFrame = 1;
if (_scrollId === -1) {
_scrollId = setInterval(_next, Math.round(duration / frames));
}
};
})();
Specifications
Specification |
---|
HTML Standard # the-location-interface |
Browser compatibility
BCD tables only load in the browser
See also
- The interface of the returned value,
Location
-
A similar information, but attached to the document,
Document.location
- Manipulating the browser history
hashchange
Redirecting to a URL is one of the most common activities performed by JavaScript. As such, JavaScript offers multiple different ways to support redirects from the code level. In this article we’ll look at how to change a URL using JavaScript, reviewing each of the potential methods in turn.
1. Using the Location Interface
The first approach uses the Location interface. Take the following sample JavaScript code and HTML markup:
JavaScript
function goGoogle() { window.location = 'http://google.com' }
HTML
<button onclick="goGoogle()">Google it</button>
When the button defined in the HTML above is clicked, it invokes function goGoogle(). This function modifies the window object’s location property, which redirects the user to the main Google Search page.
Syntax
The syntax for redirecting via window.location is as follows:
window.location = URL
This code is flexible, and will work perfectly fine even if you omit the keyword window. Additionally, you can set the href property of location, which will also perform the desired redirect.
Location methods
The location property has several useful methods associated with it. Below are three of the most commonly-used methods:
- location.assign(URL): This method redirects the user to the specified URL. The user’s browser history will be updated with the new URL visited.
- location.reload(URL): This method refreshes the current page.
- location.replace(URL): This method, similar to assign, redirects the user to the specified URL. The critical difference is that the replace() method does not update the user’s browser history (more detail below), preventing the user from navigating back to the current page. This can be helpful when you need to hide a page from being exposed to the user.
Note: In all cases above, the URL parameter is a String.
2. Using the History API
The second approach to changing the URL is using the History API. The browser’s session history is accessible via the history object in JavaScript. This object has several methods, three of which we explore below:
- back() – this method navigates the user back one entry in their browser history, as though the user pressed the “back” button in their browser.
- forward() – this method navigates the user forward one entry in their browser history, as though the user pressed the “forward” button in their browser.
- go(target) – this takes a user directly to an entry. This method takes a parameter, target, which controls the redirection. This can be a URL string, in which case the user is redirected to the URL specified, or a number. If a number is provided, the user is moved forwards (in the case of positive numbers) or backwards (in the case of negative numbers) in their browser history. Passing “0” to this function refreshes the page.
The following example code shows how to use the go() method to navigate the user’s browser history:
JavaScript
function go2pagesBack() { history.go(-2) }
Invoking the go2pagesBack() function is similar to pressing the browser’s back button twice, due to our choice to send “-2” as a parameter to history.go().
Note: If the user does not have enough pages in their history to accommodate the request, the go() method will redirect as far as it can. For example, if you have only one page in your history, history.go(-2) will only go back one page.
3. Create an HTML hyperlink
The final method of redirecting the user is simply creating an HTML hyperlink that controls the navigation. Take the following example HTML markup:
HTML
<a href="http://codota.com/">Codota</a>
● The <a> element defines a hyperlink, with the text between the tags being presented to the user.
● The href attribute sets the link’s destination, redirecting the user to the provided URL.
This method uses HTML only, but can be easily modified as needed using JavaScript.
Note: It is possible to change the href attribute, for instance, by using the setAttribute() method.
Related Articles:
JavaScript – How to Use setAttribute
JavaScript – How to Change CSS
JavaScript – How to Get Cookies
Как заменить ссылку в «href» с помощью javascript? Проведем несколько примеров. заменим ссылку в href, потом заменим текст, и последним заменим и текст и ссылку по одному нажатию!
Как заменить адрес ссылки «href» javascript
Огромное количество способов «заменить адрес ссылки javascript».
Рассмотрим пример изменения адресы в атрибуте href через javascript.
Нам понадобится :
Возьмем тег div.
Поместим вовнутрь onclick с функцией.
<button onclick=»changeURL()»>Изменить адрес</button>
Далее нам понадобится ссылка, где у нас есть атрибут «href» и обратиться к тегу через id .
<a href=»https://ya.ru/» id=»yandex»>Yandex</a>
далее нам нужно написать ту самую функцию — она будет очень простая :
<script>
function changeURL(){
document.getElementById(«yandex»).href=»https://google.com»;
}</script>
Стенд для визуализации процесса замены ссылки в реальном времени.
У нас будет вот такая ссылка :
<a href=»https://ya.ru/» id=»yandex»>Yandex</a>
Чтобы увидеть замену ссылки в реальном времени — нажмите на кнопку «Изменить адрес» и смотрите на адрес выше данной строки.
Пример ссылки с измененным адресом ссылки
И теперь та же самая ссылка уже в коде:
Как заменить текст в ссылке
Возьмем этот же пример, только чуть его модернизируем! Напоминаю, что вы можете взять любой способ onclick и обратиться к тегу
Изменим внутри тега название функции :
<button onclick=»changeURL_1()»>Изменить текст</button>
В теге ссылки изменим id — должен быть уникальным.
<a href=»https://ya.ru/» id=»yandex1″>Yandex</a>
И немного javascript :
<script>
function changeURL_1(){
document.getElementById(«yandex1″).innerHTML =»Новый текст»;
}
</script>
Тестируем замену текста в ссылке :
Yandex
Замена текста в ссылке и адреса в «href» javascript
И третьим пунктом следим оба скрипта в один, чтобы мы смогли по одном нажатию заменить и текст и адрес ссылки.
Кнопка :
<button onclick=»changeURL_2()»>Изменить адрес и текст</button>
Ссылка :
<a href=»https://ya.ru/» id=»yandex2″>Yandex</a>
javascript :
<script>
function changeURL_2(){
document.getElementById(«yandex2″).href=»https://google.com»;
document.getElementById(«yandex2″).innerHTML =»GOOGLE»;
}
</script>
Результат:
Yandex
javascript заменить текст во всех ссылках
Если мы заменяли текст в определенной ссылке, то почему бы не заменить текст во всех ссылках!?
Сделаем кнопку, чтобы было видно добавление текста ссылкам :
<button onclick=»send_atr();»>button</button>
Добавим атрибут style с цветом красный — red
function send_text()
{
var links = document.querySelectorAll(«a»);
links.forEach(link => {
link.innerHTML = «Новое содержимое во всех ссылках»;
})
}
}
Добавим вторую , чтобы изменить содержание текст а ссылки ещё раз…
И две ссылки для наглядности.
Чтобы увидеть изменение текста ссылки, две подопытные ссылки
Подопытные ссылки :
текст
текст
Кнопки для добавления всем ссылкам атрибута.
javascript заменить адрес во всех ссылках.
Следующим пунктом заменим все адреса ссылок на всей странице!
Алгоритм аналогичный!
Чтобы вы могли сделать замену ссылке нажав по кнопке, нам потребуется такая кнопка button + onclick с функцией:
<button onclick=»send_newlink();»>Добавим новый адрес во все ссылки</button>
javascript
Опять немного javascript…
function send_newlink()
{
var links = document.querySelectorAll(«a»);
links.forEach(link => {
link.href=»https://google.com»;
})
}
Результат замены, чтобы протестировать замену ссылок на всей странице нажмите по кнопке, а потом по любой ссылке… либо откройте исследовать элемент и сможете наблюдать в процессе, за любой ссылкой..