Как изменить url адрес javascript

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? ...

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.

Viktor Borítás's user avatar

asked Sep 25, 2008 at 22:00

Steven Noble's user avatar

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 Crumley's user avatar

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

moonshadow's user avatar

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]

HoldOffHunger's user avatar

answered Sep 25, 2008 at 22:07

Paul Dixon's user avatar

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:

  1. 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.

  2. 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.

  3. 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.

Community's user avatar

answered Oct 8, 2013 at 21:04

Ilia's user avatar

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 Larson's user avatar

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 Hill's user avatar

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

sam's user avatar

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 Joshi's user avatar

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's user avatar

Drew Noakes

295k162 gold badges671 silver badges736 bronze badges

answered Mar 31, 2009 at 20:33

user58670's user avatar

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 Trush's user avatar

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 Hey's user avatar

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.

Viktor Borítás's user avatar

asked Sep 25, 2008 at 22:00

Steven Noble's user avatar

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 Crumley's user avatar

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

moonshadow's user avatar

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]

HoldOffHunger's user avatar

answered Sep 25, 2008 at 22:07

Paul Dixon's user avatar

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:

  1. 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.

  2. 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.

  3. 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.

Community's user avatar

answered Oct 8, 2013 at 21:04

Ilia's user avatar

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 Larson's user avatar

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 Hill's user avatar

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

sam's user avatar

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 Joshi's user avatar

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's user avatar

Drew Noakes

295k162 gold badges671 silver badges736 bronze badges

answered Mar 31, 2009 at 20:33

user58670's user avatar

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 Trush's user avatar

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 Hey's user avatar

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?

Sajal Soni

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

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

На этом уроке мы познакомимся с объектом location, который может использоваться для получения или изменения текущего адреса страницы (URL).

Объект location — это один из дочерних объектов window, который отвечает за адресную строку окна или вкладки браузера. Доступ к данному объекту осуществляется как к свойству объекта window, т.е. через точку.


window.location

Объект location содержит свойства и методы, с помощью которых Вы можете не только получить текущий адрес страницы (URL или его части: имя хоста, номер порта, протокол и т.д.), но и изменить его.

Свойства объекта location

Свойства объекта location:

  • hash — устанавливает или возвращает якорную часть (#) URL;
  • host — устанавливает или возвращает имя хоста и номер порта URL;
  • hostname — устанавливает или возвращает имя хоста URL;
  • href — устанавливает или возвращает содержимое URL;
  • origin — возвращает протокол, имя хоста и номер порта URL;
  • pathname — устанавливает или возвращает часть URL, содержащей путь;
  • port — устанавливает или возвращает номер порта URL;
  • protocol — устанавливает или возвращает протокол URL;
  • search — устанавливает или возвращает часть URL, содержащей строку с параметрами (?параметр1=значение1&параметр2=значение2&…);

В качестве примера рассмотрим следующую адресную строку (URL):

JavaScript - Объект location

Примечание: Изменение URL или какой либо её части с помощью свойств объекта location приводит к немедленному переходу к этому URL в текущем окне, или в том окне или вкладке браузера, для которого этот объект был вызван.

Например, изменить href на http://itchief.ru для текущего окна:

window.location.href = "http://itchief.ru";
//для текущего окна "window." можно опустить
location.href = "http://itchief.ru";
//кроме этого свойство href тоже можно опустить, т.к. location == location.href
location = "http://itchief.ru";

Например, изменить href для окна с именем myWindow:

//откроем новое окно с помощью метода JavaScript open()
var myWindow = window.open("","","height=300,width=400");
//изменим location окна, идентификатор которого хранится в myWindow
myWindow.location.href = "http://itchief.ru";

Например, вывести на экран все свойства и методы объекта location и их значения для текущей веб-страницы.

<div id="propertiesLocation" class="alert alert-warning"></div>

<script>
  var stringPropertiesLocation = "";
  for (var property in location)
  {
    stringPropertiesLocation += "Свойство/метод: <strong>" + property + "</strong>. ";
    stringPropertiesLocation += "Значение: <strong>" + location[property] + "</strong> ";
    stringPropertiesLocation += "<strong>Тип: </strong>" + typeof location[property]; 
    stringPropertiesLocation += "<br />";
  }
  document.getElementById("propertiesLocation").innerHTML = stringPropertiesLocation;
</script>

Методы объекта location

Методы:

  • assign() — загружает новый документ в текущее окно (вкладку) браузера или в то окно для которого этот метод был вызван.
  • reload() — перезагружает текущий документ. Метод reload() имеет один необязательный параметр булевского типа. Если в качестве параметра указать значение true, то страница будет принудительно обновлена с сервера. А если параметр не указывать или использовать в качестве параметра значение false, то браузер может обновить страницу, используя данные своего кэша. Метод reload() «имитирует» нажатие кнопки обновить в браузере.
  • replace() — заменяет текущий документ с помощью нового документа, URL которого указан в качестве параметра.

Рассмотрим следующие примеры:

1. При нажатии на ссылку загрузим в 1 фрейм страницу http://nigma.ru/:

<script>
  function loadNigma() {
    window.frames[0].location.assign("http://nigma.ru/");
  }
</script>
...
<!-- Загрузить URL http://yandex.ru в 1 фрейм -->
<a href="javascript:loadNigma()">Загрузить nigma во фрейм</a>
<hr />
<iframe width="500" height="400"></iframe>

2. Откроем новое окно, в котором будем управлять адресной строкой с помощью методов объекта location:

<script>
  let newWindow;
  function openWindow() {
    if (!newWindow) {
      newWindow = window.open('https://itchief.ru/', '', 'width=400,height=500');
      newWindow.focus();
    } else {
      newWindow.focus();
    }
  }
  function assignWindow() {
    if (newWindow) {
      newWindow.location.assign('https://itchief.ru/javascript/');
      newWindow.focus();
    }
  }
  function replaceWindow() {
    if (newWindow) {
      newWindow.location.replace('https://itchief.ru/html-and-css/');
      newWindow.focus();
    }
  }
</script>

<ul>
  <li><a href="javascript:openWindow()">Создать окно «https://itchief.ru/»</a></li>
  <li><a href="javascript:assignWindow()">Загрузить «https://itchief.ru/javascript/»</a></li>
  <li><a href="javascript:replaceWindow()">Заменим страницу на «https://itchief.ru/html-and-css/»</a></li>
</ul>

Понравилась статья? Поделить с друзьями:
  • Как изменить url react
  • Как изменить ttl на пс4
  • Как изменить url linkedin
  • Как изменить ttl на планшете
  • Как изменить uptime windows