- Шпаргалка по window.location
- How to extract hash substring values from window.location and write them into HTML?
- 1 Answer 1
- Setting JavaScript window.location
- 3 Answers 3
- What is location.search in javascript
- 7 Answers 7
- How to listen for changes to window.location.search in 2019
- 1 Answer 1
- Final Answer:
- Best Answer I can come up with (Second Attempt):
- First Attempt at an Answer:
Шпаргалка по window.location
Ищешь данные URL сайта, тогда объект
как раз для тебя! Используй его свойства для получения информации об адресе текущей страницы или используй его методы для редиректа, перезагрузки некоторых страниц 💫
В моем примере выше ты заметишь, что
возвращают одно и то же значение. Так в чем же разница. Ну, это связано с номером порта. Давай взглянем.
будет содержать номер порта, тогда как
будет возвращать только имя хоста.
Ты можешь не только вызвать свойства объекта
чтобы получить информацию об URL. Ты можешь использовать его для установки новых свойств и изменения URL. Посмотрим, что я имею в виду.
Вот полный список свойств, которые ты можешь изменить:
Единственное свойство, которое ты не можешь установить, это
Это свойство доступно только для чтения.
который дает тебе информацию о текущем местоположении страницы. Ты также можешь получить доступ к объекту Location несколькими способами.
Объект доступен таким образом, потому что является глобальной переменной в браузере.
Каждый из 4х свойств выше указывают на один и тот же объект
Я лично предпочитаю
и на самом деле не буду использовать
Главным образом потому, что
читается больше как общий термин, и кто-то может случайно назвать свою переменную, которая переопределяет глобальную переменную. Взять, к примеру:
Я думаю, что большинство разработчиков знают, что
является глобальной переменной. Так что у тебя меньше шансов вызвать путаницу. Поэтому я рекомендую использовать
Вот мой личный порядок предпочтений:
Конечно, это всего лишь мои предпочтения. Ты эксперт в своей кодовой базе, лучшего способа нет, лучший всегда тот, который подходит тебе и твоей команде.🤓
Вот определение из MDN
Этот метод возвращает USVString URL. Версия только для чтения
Другими словами, ты можешь использовать его для получения значения
Что касается использования, я не смог найти много информации о том, что лучше; но если ты это сделаешь, пожалуйста, поделись в комментах 😊. Я нашел тест производительности на разницу.
Один момент, который я хочу отметить в отношении этих тестов скорости, заключается в том, что они зависят от браузера. Различные браузеры и версии будут иметь разные результаты. Я использую Chrome, поэтому href вышел быстрее остальных. Так что я буду этим пользоваться. Также я думаю, что он читается более явно, чем
Совершенно очевидно, что
предоставит URL, тогда как
выглядит как нечто, преобразуемое в строку.😅
Оба эти метода помогут тебе перейти по другому URL. Разница в том, что
сохранит твою текущую страницу в истории, поэтому твой пользователь может использовать кнопку «назад» для перехода к ней. Принимая во внимание метод
он не сохраняет его истории. Это немного смущает, да? Меня тоже. Давай пройдемся по примерам.
Мне просто нужно подчеркнуть «текущая страница» в определении. Это страница прямо перед
Теперь ты знаешь, что мы можем изменить свойства
присвоив значение с помощью
Точно так же существуют методы, к которым мы можем получить доступ для выполнения некоторых действий. Итак, что касается «как перенаправить/редиректить на другую страницу», то есть 3 способа.
replace vs assign vs href
Все три перенаправляют, разница связана с историей браузера.
здесь одинаковы. Они сохранят твою текущую страницу в истории, а
— нет. Так что, если ты предпочитаешь опыт создания, когда навигация не может вернуться на исходную страницу, используй
Таким образом, вопрос сейчас:
Я считаю, что это личные предпочтения. Мне больше нравится
потому что это метод, поэтому мне кажется, что я выполняю какое-то действие. Также есть дополнительный бонус в том, что его проще тестировать. Я писал много Jest-тестов, поэтому, используя метод можно просто замокать данные.
Но для тех, которые болеют за
для редиректа страницы. Я нашел тест производительности и он работает в моей версии Chrome быстрее. Опять же, тесты производительности варьируются в зависимости от браузера и разных версий, сейчас это может быть быстрее, но, возможно, в будущих браузерах всё может измениться.
Как это все появилось 👍
Ладно, я готов с вами поделиться как появилась эта шпаргалка. Я гуглил, как редиректить на другую страницу, и столкнулся с объектом
Иногда я чувствую, что разработчик является журналистом или детективом — для того, чтобы собрать всю доступную информацию, приходится много копаться и прочесывать разные источники. Честно говоря, я был ошеломлен материалами, они все были “о разном”, а я просто хотел всё из одного источника. Я не мог найти много полной информации, поэтому я подумал, а расскажу-ка я об этом в шпаргалке!
Ещё больше полезного в наших соц. сетях instagram, facebook, telegram
How to extract hash substring values from window.location and write them into HTML?
I’m trying to extract hash substring values from window.location and write them into HTML for the user to see, with an URL syntax that disallows use of ? as query string delimiter.
So I am working with this simple page:
I call the page with an URL that looks like this, this the client window.location:
I want to write FOO, BAR, FRED into the page, so the user can see it.
(notice no ? in the URL as query string delimiter, just # )
. On input button click, I get a successful alert (as expected) that shows the source «FOO» from the URL. Great.
But how do I get the other two SParamaterNames, and then how do I write them into the page as HTML for the user to see, rather than return an alert?
UPDATE UPDATE UPDATE (below)
Thanks, @sam-baker!! . Great answer. I used your first example, but changed the first two lines in your code to $(window).load(function() < so that the script runs onload, which was my intent.
So, I am still using this same URL:
But I want to insert the hash substring values into hardcoded HTML, like this:
I will style each value individually, by hardcoding span or div styles into the HTML.
UPDATE UPDATE UPDATE
Here’s the solution:
Hit the following simple page in the code example bellow with this URL syntax, and it will output the substring vars to the user, onload, wherever you want them on the page.
Had some crossbroswer issues because innerText is not supported by Firefox, did not want to deal with cross-browser fallback to textContent , etc, so just walked DOM tree and created text nodes, replacing the + unicode character with space. Hope this is useful to you!
1 Answer 1
You’re only requesting the first of the 3 parameters using:
If you want all 3 parameters and you know the names, you can use:
To add those vars to the page, you can insert them in divs like this:
That version queries each of the 3 tags and creates a new div in the page for that tag with the tag’s value as the content.
It also adds a CSS class, query-string-param to those divs so that you can style the text — presumably you’ll want to do that, and add more HTML to each div since it’s not clear why that text is displayed.
If you don’t know the query string keys upfront (source, medium and campaign), you could use a function I created, GetAllURLParameters that returns an array of objects with both the key («source») and the value («FOO») for each param.
That would look like this:
Which then shows the names and values of all query parameters.
UPDATE
Since you already have hardcoded HTML that looks like this:
The easiest way to insert your values would be to add an id to each of those spans:
Then after you query the parameters, you can insert them like this:
Setting JavaScript window.location
I’m currently setting the window.location.pathname property to redirect the user to a relative URL. The new URL has parameters, so the line of JavaScript looks like this:
This is successful in Firefox, however Chrome encodes the question mark with ‘%3F’ and the request subsequently fails.
I’m not sure if I’m using window.location properly. Do I need to use properties of window.location such as pathname or href? I’ve found that as soon as I set one property the location is reloaded, so for example, the search and pathname properties can’t be set separately. Can window.location be set directly? I only need to set a relative URL with a parameter.
3 Answers 3
pathname and many other properties of location and links reflect only part of the URL:
As you can see, the . part of the URL is not part of the pathname ; it makes no sense to write a value containing ? to location.pathname , as that part of a URL cannot contain a question mark. Chrome is correcting your mistake by encoding the character to a sequence that means a literal question mark, which doesn’t terminate pathname .
These properties are great for breaking a URL into their constituent parts for you to process, but you probably don’t want to write to them in this case. Instead, write to location.href . This represents the whole URL, but it’s perfectly fine to write a relative URL to it; this will be worked out relative to the current value, so there is in fact no need to read and split the pathname at all:
Note the URL-encoding. If a username can contain characters other than alphanumerics you will probably need this to stop those characters breaking the parameter. Always URL-encode arbitrary strings before putting them into part of a URL.
What is location.search in javascript
I want to know what location.search.substring(1) actually does. I saw this code on some website. I tried to print using alert , but this did not give any result. Is it supposed to alert location href?
7 Answers 7
So that code will return the entire query parameters without the question mark.
The location.search property contains the query string of an URI (including the ?), if any.
So your code snips away the leading ? and returns param=arg .
The search property returns the query portion of a URL, including the question mark (?).
That means, that location.search.substring(1) should return the data without the question mark.
The «query porpotion» is the query string:
e.g. if you have the following url
then window.location.search will return ?Browser=Netscape as a string
location.search returns a query string including the initial question mark. The substr method is to remove the initial question mark from the returned query string.
The reason why you’re not getting any results in the alert() is because you’re trying to read query string on a website which doesn’t have any.
Here’s how you test:
- Go to this URL
- Open up the console on your browser
- Paste the code snippet shared below and hit enter
Old question but the answer might be helpful for new visitors on this page.
How to listen for changes to window.location.search in 2019
I would like to update window.location.search without reloading the document and then execute a function based on the updated values in window.location.search .
When the user clicks a button, that button’s onclick event fires the following function:
So far so good. The window.location.search updates in the browser URL bar.
But I can’t find a general background event listener which detects this update — something like onhashchange but for query strings.
The best I can come up with is:
This works but I’m convinced there must be a more elegant approach.
1 Answer 1
Final Answer:
I was mostly happy with the Second Attempt answer immediately below.
But I really didn’t like:
which I adopted to trigger the popstate event, manually.
In practice, I found this hack worked sometimes, it was slow at other times and on occasion it failed completely.
On paper, it feels too makeshift.
After repeatedly searching and experimenting (this was remarkably hard to find), I have finally found the correct syntax for manually firing a popstate event.
It’s as simple as dispatching this:
So the final code is:
Best Answer I can come up with (Second Attempt):
Building on the following:
I know for certain that the query-string will only need to be checked either:
when the page loads or reloads;
when window.history.pushstate is invoked;
or when (as @Kaiido astutely pointed out in the comments below) a page is accessed via the forward and back buttons
I also know that:
- The window.load event listener covers Point 1.;
- The window.popstate event listener covers Point 3.;
This only leaves Point 2.
Dealing with Point 2
As MDN reports:
Note that just calling history.pushState() or history.replaceState() won’t trigger a popstate event. The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).
But this means that rather than using (as in my first attempt, below):
I can use instead:
This means that rather than needing to invoke the function directly, I can now allow the same window.popstate event listener covering Point 3 to do its work, giving me cleaner, more logically separated code.
N.B. I find it. weird. that pressing the forward button alone will fire the window.popstate event listener, but invoking window.history.pushState() will not. (necessitating the immediately subsequent addition of history.back(); history.forward(); to duplicate the functionality of a forward button).
But, as above, this is the best, cleanest, most optimised (in terms of logical separation and future code maintenance) solution I can come up with. If anyone has a dramatically better idea, I’ll be happy to transfer the green tick.
First Attempt at an Answer:
I am tentatively concluding that there is no way to achieve this effect using a background event listener which can detect when the query string updates.
Instead, since I know for certain that the query-string will only need to be checked either: