> For the complete documentation index, see [llms.txt](https://docs.exoclick.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.exoclick.com/tutorials/ru/uchebnye-materialy/uchebnye-materialy-dlya-izdatelei/dynamically-block-ads-using-data-block-ad-types.md).

# Как динамически блокировать типы рекламы с помощью data-block-ad-types

Как издатель, вы можете захотеть контролировать, какие типы рекламы показываются вашим посетителям, в зависимости от определённых условий, таких как аутентификация пользователя, настройки предпочтений пользователя или другие факторы. В этой статье мы демонстрируем два фрагмента кода, показывающих, как можно динамически управлять тем, какие типы рекламы отображаются или блокируются в вашей рекламной зоне ExoClick.

Чтобы сделать это возможным, мы используем **data-block-ad-types** функцию ExoClick и даём ей динамическое управление несколькими рекламными местами без необходимости сложной интеграции с серверной частью.

## ПРИМЕР 1 - Динамическое отображение рекламы на основе ввода пользователя

Этот метод идеально подходит для настройки ограничений рекламы на основе согласия пользователя. Когда посетитель соглашается с вашими условиями, его предпочтение сохраняется в браузере в `localStorage`. Это действие навсегда изменяет настройки рекламы для этого пользователя при всех последующих посещениях, позволяя показывать более широкий набор типов рекламы после получения согласия.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <script>
      const adZoneConfigs = [
        { containerId: "zid-5662140", class: "eas6a97888e20", zoneid: "5662140" },
        { containerId: "zid-5532602", class: "eas6a97888e2", zoneid: "5532602" },
      ];

      // ИЗМЕНЯЙТЕ ЗАБЛОКИРОВАННЫЕ ТИПЫ РЕКЛАМЫ НА ОСНОВЕ БУЛЕВОГО ЗНАЧЕНИЯ И ПЕРЕРИСОВЫВАЙТЕ РЕКЛАМУ
      let updateAdRestrictions = (value) => {
        if (value === true) {
          adZoneConfigs.forEach((adZone) => {
            let adContainer = document.getElementById(adZone.containerId);
            adContainer.innerHTML = "";
            adContainer.innerHTML = `
            <ins class="${adZone.class}" data-zoneid="${adZone.zoneid}" data-block-ad-types=""></ins>

            `;
            (AdProvider = window.AdProvider || []).push({ serve: {} });
          });
        }
        return;
      };
    </script>
  </head>
  <body>
    <h1>ТЕСТОВАЯ СТРАНИЦА</h1>

    <!-- ПРИНЯТЬ УСЛОВИЯ И ДОБАВИТЬ СОГЛАСИЕ В LOCAL STORAGE ПРИ НАЖАТИИ -->
    <button
      id="accept-terms-button"
      onclick="updateAdRestrictions(true); localStorage.setItem('acceptTerms', true); this.remove();"
    >
      Я принимаю условия и положения
    </button>

    <main>
      <script
        async
        type="application/javascript"
        src="https://a.magsrv.com/ad-provider.js"
      ></script>

      <h2>zid-5662140</h2>
      <div id="zid-5662140">
        <ins
          class="eas6a97888e20"
          data-zoneid="5662140"
          data-block-ad-types="101"
        ></ins>

        <script>
          (AdProvider = window.AdProvider || []).push({ serve: {} });
        </script>
      </div>

      <h2>zid-5532602</h2>
      <div id="zid-5532602">
        <ins
          class="eas6a97888e2"
          data-zoneid="5532602"
          data-block-ad-types="101"
        ></ins>
        <script>
          (AdProvider = window.AdProvider || []).push({ serve: {} });
        </script>
      </div>
    </main>

    <!-- ПРОВЕРЬТЕ LOCAL STORAGE НА НАЛИЧИЕ ПОДТВЕРЖДЁННОГО COOKIE И ВЫЗОВИТЕ updateAdRestrictions, ЕСЛИ ПОЛЬЗОВАТЕЛЬ УЖЕ ПОДТВЕРЖДЁН -->
    <!-- ДОЛЖНО БЫТЬ РАЗМЕЩЕНО ПОСЛЕ СКРИПТОВ РЕКЛАМНЫХ ЗОН -->
    <script>
      const cookie = localStorage.getItem("acceptTerms");
      const parsedCookie = JSON.parse(cookie)
      if (parsedCookie === true) {
        updateAdRestrictions(true);
        document.getElementById("accept-terms-button").remove();
      }
    </script>
  </body>
</html>
```

## ПРИМЕР 2 - Динамическое отображение рекламы на основе параметра URL

Этот подход эффективен для изменения настроек рекламы на основе параметра URL. Например, после аутентификации пользователя его можно перенаправить на URL, содержащий такой параметр, как `?user_verified=1`. Этот параметр сообщает странице, что пользователь подтверждён, и система начинает показывать для этой сессии менее ограничительные типы рекламы.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Тестовая страница</title>
  </head>

  <body>
    <header>
      <ins
        class="eas6a97888e20"
        data-zoneid="5662140"
        data-block-ad-types="101"
      ></ins>

      <script
        async
        type="application/javascript"
        src="https://a.magsrv.com/ad-provider.js"
      ></script>

      <script>
        (AdProvider = window.AdProvider || []).push({ serve: {} });
      </script>
    </header>

    <footer id="footer-ads">
      <script
        async
        type="application/javascript"
        src="https://a.magsrv.com/ad-provider.js"
      ></script>

      <ins
        class="eas6a97888e2"
        data-zoneid="5532602"
        data-block-ad-types="101"
      ></ins>

      <script>
        (AdProvider = window.AdProvider || []).push({ serve: {} });
      </script>
    </footer>

    <script>
      const userVerified = new URLSearchParams(window.location.search).get(
        "user_verified"
      );
      const headerElement = document.querySelector('[data-zoneid="5662140"]');
      const footerElement = document.querySelector('[data-zoneid="5532602"]');
      const elementsArr = [headerElement, footerElement];
      if (userVerified == 1) {
        elementsArr.forEach((element) => {
          element.setAttribute("data-block-ad-types", "");
          const newElement = element.cloneNode(true);
          element.parentNode.replaceChild(newElement, element);
        });
      }
    </script>
  </body>
</html>
```


---

# 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://docs.exoclick.com/tutorials/ru/uchebnye-materialy/uchebnye-materialy-dlya-izdatelei/dynamically-block-ads-using-data-block-ad-types.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.
