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
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
KISS_ARMY 1 / 1 / 3 Регистрация: 03.07.2013 Сообщений: 278 |
||||||||
1 |
||||||||
Поменять адрес ссылки07.11.2016, 08:12. Показов 8308. Ответов 3 Метки нет (Все метки)
Добрый
Я залил себе на сайт этот скрипт в корень
а как можно указать без url мой сайт?
__________________
0 |
511 / 485 / 161 Регистрация: 08.07.2013 Сообщений: 1,714 Записей в блоге: 1 |
|
07.11.2016, 10:38 |
2 |
«/путь_до_скрипта»
0 |
zuluss 28 / 28 / 8 Регистрация: 23.12.2015 Сообщений: 97 |
||||
07.11.2016, 18:06 |
3 |
|||
если скрипт в корне то достаточно
0 |
Заблокирован |
|
08.11.2016, 03:02 |
4 |
Не достаточно. Добавлено через 4 минуты
0 |
Гипертекстовые ссылки, связывая страницы сайтов в единую сеть, делают возможным существование Интернета в его сегодняшнем виде. А в сегодняшней жизни нет явления более изменчивого, чем всемирная сеть. Это вызывает необходимость довольно часто приводить ссылки в соответствие с изменениями сети. Как изменить ссылку на вашем сайте мы и рассмотрим подробней.
Инструкция
Ссылки, как и все остальные элементы страницы сайта, визуализируются браузером на основе информации присылаемой ему сервером. Эта информация представляет собой набор инструкций на языке HTML (HyperText Markup Language — «язык разметки гипертекста»), описывающих типы, внешний вид и расположение каждого элемента веб-страницы. Программисты называют инструкции языка HTML «тегами». Простая ссылка создается браузером, когда он читает из кода страницы такой тег:<a href=»page.html»>Текстовая ссылка</a>Здесь <a href=»page.html»> — открывающий тег ссылки, а </a> — закрывающий. В открывающий тег помещают дополнительную информацию — «атрибуты» этого тега. Атрибут href содержит адрес страницы (или другого файла), на который должен быть отправлен запрос, если посетитель нажмет ссылку. Если запрашиваемая страница или файл лежит в этой же папке сервера (или вложенной в нее), то не обязательно указывать полный адрес — достаточно его имени или пути к вложенной папке. Такие адреса называют «относительными», а полные — «абсолютными». Ссылка с абсолютным адресом может выглядеть так:<a href=»http://site.ru/page.html»>Текстовая ссылка</a>
То есть, чтобы изменить ссылку, вам следует открыть html-код страницы, лежащей на сервере, найти в нем тег нуждающейся в замене гиперссылки и изменить содержимое атрибута href.
Если файл, содержащий код страницы есть в вашем распоряжении, то открыть и отредактировать его можно любым текстовым редактором, например стандартным Блокнотом. Если же вы пользуетесь системой управления сайтом, то редактировать страницы можете прямо в браузере. Для этого надо найти в панели управления сайтом редактор страниц и открыть в нем нужную страницу.
Такой редактор страниц может иметь режим визуального редактирования — его иногда называют WYSIWYG (What You See Is What You Get — «что видишь, то и получишь»). В этом случае редактировать html-код не понадобится. Страница в таком редакторе выглядит так же как и на сайте, достаточно найти на ней нужную ссылку, выделить ее и, нажав соответствующую кнопку на панели редактора, изменить адрес ссылки. Расположение этой кнопки зависит от типа визуального редактора, используемого вашей системой управления — их довольно много.
Кроме адреса, у тега ссылки есть и другие атрибуты, которые позволяют менять поведение и внешний вид ссылки. Наиболее часто возникает необходимость менять атрибут target — он указывает, в которое окно нужно загружать новую страницу. Есть всего четыре варианта:_self — страницу следует загружать в это же окно или фрейм. «Фреймами» называют каждую часть окна браузера, если страница делит его на несколько частей;_parent — если страница, где находится ссылка, сама была загружена из другого окна (или фрейма), то она имеет «родительское» окно. Значение _parent указывает, что страница, на которую указывает ссылка, должна загружаться в то самое родительское окно;_top — новую страницу следует загрузить в это же окно, уничтожив любые фреймы (если они есть);_blank — указывает, что для перехода по этой ссылке надо открывать отдельное окно;Например:<a href=»page.html» target=»_blank»>Ссылка откроется в новом окне</a>
Источники:
- как и что изменить
Войти на сайт
или
Забыли пароль?
Еще не зарегистрированы?
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.