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
Адрес и название сайта обычно выбираются в самом начале раз и навсегда. Редко приходится их менять. Но при необходимости это сделать можно. Рассмотрим в данной статье, как это сделать.
Но для начала следует уточнить теоретические вопросы.
Адрес сайта – это url, который показывается в адресной строке браузера, который посетитель пишет, чтобы попасть к вам на ресурс, который знают поисковики.
А название сайта – это title вашего ресурса, это просто слово, которым он называется.
Например, сайт 123456789.ru имеет адрес http://123456789.ru, а название «просто девять цифр».
Как поменять название сайта
В WordPress это сделать очень легко. Нужно перейти в консоли в «Настройки» – «Общие», и там поменять текст в строке «Название сайта». За одно изменить можно и «Короткое описание», если с названием поменялась и тематика.
Сохранить изменения, и всё.
Как поменять адрес сайта
После покупки и регистрации нужного доменного имени, следует заняться настройками в базе данных.
Здесь необходимо изменить адреса в параметрах home и siteurl – вписать новые. После этих изменения вы можете найти свой сайт на новом адресе.
Однако помните, если вы поменяете данные в этих строках, не перенеся сайт на другой домен, то по старому url, вы его уже не найдёте, и по новому, естественно, тоже. То есть сайт не будет загружаться ни по какому из адресов.
Как поменять адрес сайта и не потерять аудиторию
Наилучшим методом для того, чтобы сменить адрес сайта является редирект 301. С помощью данного способа можно изменить url сайта и не беспокоить о том, что ресурс потеряет свою целевую аудиторию или индексацию в поисковиках.
Если изменить адрес сайта, не используя редирект 301, то ресурс неизбежно потеряет большую часть постоянных посетителей, если они, конечно же, не будут заблаговременно извещены о смене адреса. Хотя, это плохой метод. Ведь поисковые роботы всё равно будут не в курсе о смене ваше адреса.
Когда изменять адрес сайта можно безопасно
Очевидно, что на начальном этапе, на первых порах, когда у сайта ещё нет нормальной стабильной аудитории и поисковиками он ещё не проиндексирован, можно смело менять адрес сайта, как угодно, и никаких потерь от этого не будет.
Если же поисковики уже хорошо работают с вашим ресурсом, и есть большая аудитория, которая постоянно к вам приходит, то вам необходимо задуматься о том, стоит ли смена адреса сайта таких головных болей, связанных с переездом.
Для изменения URL страницы сайта вам необходимо перейти на страницу, где вы собираетесь изменить URL, после этого из верхнего меню нажать на кнопку МЕТА-теги: и в открывшемся окне вписать в поле новый URL:
Поле URL должно содержать латинское написание, без пробелов.
Внимание! После редактирования полей не забудьте сохранить изменения.
Для изменения Title, Description, Keywords ознакомьтесь с описанием данных полей.
Данные свойства необходимы поисковым системам, пожалуйста, не забывайте их заполнять!
Описание свойств:
- Url — часть адреса страницы сайта. Адреса страницы строятся в UMI.CMS автоматически, в данном примере адрес страницы будет выглядеть следующим образом: «http://help-cms.ru/site_manager/faq/kak_izmenit_url_stranicy_sajta/«
-
Поле Title — Этот мета-тег выполняет множество задач, как прямо, так и косвенно. В результатах поиска по ключевым словам поисковые системы используют заголовок страницы для указания ссылки на данный документ. Интересно написанный заголовок, содержащий ключевые слова, привлечет больше внимания посетителей и увеличит шансы на то, что сайт посетит больше людей. По тексту заголовка пользователь получает дополнительную информацию о сайте, на котором он находится, и о названии текущей страницы. Не стоит думать, что достаточно в документе указать логотип сайта и проигнорировать заголовок, ведь посетитель может свернуть окно. В свернутом виде заголовок также отображается на кнопках панели задач, поэтому можно легко ориентироваться между свернутыми окнами сайтов,а не перелистывать их по очереди.
- Поле Keywords — Этот мета-тег был предназначен для описания ключевых слов, встречающихся на странице, и раньше влиял на поисковую оптимизацию. Но в результате действия людей, желающих попасть в верхние строчки поисковых систем любыми средствами, теперь дискредитирован. Поэтому многие поисковые системы пропускают этот параметр. Ключевые слова можно перечислять через пробел или запятую. Поисковые системы сами приведут запись к виду, который они используют.
- Поле Description — Большинство поисковых серверов отображают содержимое поля description при выводе результатов поиска. Если этого тега нет на странице, то поисковый движок просто перечислит первые встречающиеся слова на странице, которые, как правило, оказываются не всегда верно отражающими содержание страницы.
Правильное заполнение Title:
Семантическое ядро для сайта, правильное заполнение тегов title, description, keywords с примерами
Неправильное заполнение:
семантическое ядро для сайта, правильный title, подбор ключевых слов, заполнение тегов, семантическое ядро
или
-=ваш сайт=-семантическое ядро | seo услуги, купить сайт и самый лучший seo форум
или
Семантическое ядро title description keywords и другое
Правильное заполнение Keywords:
описание для сайта, правильный title, подбор ключевых слов, заполнение мета-тегов, семантическое ядро
Неправильное заполнение:
описание, для, сайта, правильный, title, подбор, ключевых, слов, заполнение, мета, тегов
описание для сайта правильный title подбор ключевых слов заполнение мета-тегов ядро
или
описание для сайта,правильный title,подбор ключевых слов,заполнение мета-тегов,семантическое ядро
Правильное заполнение Description:
Составление семантического ядра для сайта с примерами и разъяснениями. Правильное заполнение тегов title, description, keywords. Подбор релевантных ключевых слов
Неправильное заполнение:
семантическое ядро для сайта, правильный title, подбор ключевых слов, заполнение тегов, семантическое ядро
или
Наш сайт самый-самый и если хотите на нем вы узнаете все
или
Кому на Руси жить? на выбор: хорошо, так себе, как себе так и тебе