> For the complete documentation index, see [llms.txt](https://tads.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tads.gitbook.io/docs/getting-started/publishers/embed-widget/vanilla-js.md).

# Vanilla JS

## 1. Insert widget code in the app

You can integrate the widget using native JavaScript. Add the following code to your project, ensuring that the tads script is loaded beforehand:

{% stepper %}
{% step %}

#### Insert the following script into \<head> or in the end of \<body>  in your HTML document:

```html
<script src="https://w.tads.me/widget.js"></script>
```

{% endstep %}

{% step %}

#### Insert the following `<div>` where you want to render the ad:

```html
<div id="tads-container-YOUR_WIDGET_ID"></div>
```

{% endstep %}

{% step %}

#### Add the following code for the selected format to your HTML document to initialize the widget:

### Text-Graphic Block (TGB)

```html
<script>
    const adsNotFoundCallback = () => {
        console.log('No ads found to show');
        // Write your code here in case we couldn't display ad
    };

    // Callback for REWARDED format
    const onClickRewardCallback = (adId) => {
        console.log('Clicked ad:', adId);
    };

    const adController = window.tads.init({
        widgetId: YOUR_WIDGET_ID,
        type: 'static',
        debug: false, // Use 'true' for development and 'false' for production
        onClickReward: onClickRewardCallback,
        onAdsNotFound: adsNotFoundCallback
    });

    adController.loadAd()
        .then(() => adController.showAd())
        .catch((err) => {
            console.log(err);
            adsNotFoundCallback();
        });
</script>
```

### Fullscreen banner

```html
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const WIDGET_ID = "your_widget_id";

        // Use 'true' for development and 'false' for production
        const IS_DEBUG = true;
        
        // The HTML element ID that triggers the display of ads on click.
        const btnIdSelector = "your_clickable_selector";  
        
        // Callback for REWARDED format.
        const onShowRewardCallback = (result) => {
            console.log('Show ads, reward user:', result);
        };

        // Callback for no ads response
        const onAdsNotFound = () => {
            console.log('Callback which calls if no ads found to show',);
        }

        const adController = window.tads.init({
          widgetId: WIDGET_ID,
          type: 'fullscreen',
          debug: IS_DEBUG,
          onShowReward: onShowRewardCallback,
          onAdsNotFound: onAdsNotFound,
        });
        
        // Use your button or link HTML selector for getElementById
        document.getElementById(btnSelector).addEventListener('click', () => {
          adController
            .then(() => adController.showAd())
            .catch((result) => {
              console.log(result);
            });
        });
    });
</script>
```

{% endstep %}
{% endstepper %}

<details>

<summary>Alternative widget code (async)</summary>

If you need to speed up page loading, you can use the alternative widget code that includes the `async` attribute. This setup method requires advanced setup and is recommended for experienced webmasters:

1. **Insert the following script into any place of your HTML document:**

```html
<script src="https://w.tads.me/widget.js" async></script>
```

2. **Insert the following `<div>` where you want to render the ad:**

```html
<div id="tads-container-YOUR_WIDGET_ID"></div>
```

3. **Add the following code  for the selected format after `<div>` to initialize the widget**

#### Text-Graphic Block (TGB)

```html
<script>
    const initTadsWidget = function() {
        const adsNotFoundCallback = () => {
            console.log('No ads found to show');
            // Write your code here in case we couldn't display ad
        };

        function initAdController() {
            const adController = window.tads.init({
                widgetId: YOUR_WIDGET_ID,
                debug: false, // Use 'true' for development and 'false' for production
                onShowReward: (adId) => {
                    console.log('Show ad:', adId);
                    // Write code here for reward user after ad showed or delete this func onShowReward
                },
                onClickReward: (adId) => {
                    console.log('Click on ad:', adId);
                    // Write code for reward user after ad cliked or delete this func onClickReward
                },
                onAdsNotFound: adsNotFoundCallback
            });

            adController.loadAd()
                .then(() => adController.showAd())
                .catch((err) => {
                    console.log(err);
                    adsNotFoundCallback();
                });
        }

        if (window.tads && window.tads.init) {
            initAdController();
        } else {
            let tadsInterval = setInterval(() => {
                if (window.tads && window.tads.init) {
                    clearInterval(tadsInterval);
                    initAdController();
                }
            }, 100);
        }
    };

    if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTadsWidget);
    } else {
        initTadsWidget();
    }
</script>

```

#### Fullscreen banner

```html
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const WIDGET_ID = "YOUR_WIDGET_ID"; // Replace on your WIDGET ID
    const IS_DEBUG = true; // Replace on false in production
    const BTN_ID = "your_clickable_selector"; // Replace on your button ID
    const TYPE = "fullscreen";

    let adController = null;
    let tadsReady = false;

    const onShowRewardCallback = (result) => {
      console.log("Show ads, reward user:", result);
    };

    const onAdsNotFound = () => {
      console.log("No ads found to show");
    };

    function waitForTadsReady(timeout = 5000) {
      return new Promise((resolve, reject) => {
        if (window.tads && typeof window.tads.init === "function") {
          return resolve();
        }

        const start = performance.now();
        const iv = setInterval(() => {
          if (window.tads && typeof window.tads.init === "function") {
            clearInterval(iv);
            resolve();
          } else if (performance.now() - start > timeout) {
            clearInterval(iv);
            reject(new Error("TADS widget script not loaded"));
          }
        }, 50);
      });
    }

    async function showAd() {
      try {
        if (!tadsReady) {
          await waitForTadsReady();
          tadsReady = true;
        }

        if (!adController) {
          adController =
            window.tads.controllers?.[WIDGET_ID] ||
            window.tads.init({
              widgetId: WIDGET_ID,
              type: TYPE,
              debug: IS_DEBUG,
              onShowReward: onShowRewardCallback,
              onAdsNotFound: onAdsNotFound,
            });
        }

        if (adController && typeof adController.showAd === "function") {
          adController.showAd().catch((err) => {
            console.error(`Error showing ad:`, err);
          });
        } else {
          console.warn("Ad controller not ready");
        }
      } catch (err) {
        console.error("Failed to load TADS:", err);
      }
    }

    const btn = document.getElementById(BTN_ID);
    if (!btn) {
      console.error("Button not found:", BTN_ID);
      return;
    }

    btn.addEventListener("click", showAd);
  });
</script>
```

</details>

## 2. Add your widget ID&#x20;

Replace YOUR\_WIDGET\_ID with the corresponding widget ID you received from your personal account.

## 3. Set a reward (if needed)

If you want to incentivize users to view or click on the ads, add code to the `onShowRewardCallback` and `onClickRewardCallback` and `onAdsNotFound` functions to reward the user for viewing and/or clicking, respectively.\
You can config your widget using the following parameters

<table><thead><tr><th width="160">Parameter</th><th width="97"></th><th width="104">Type</th><th width="102">Default</th><th>Description</th></tr></thead><tbody><tr><td>id</td><td>required</td><td>string</td><td></td><td>Your widget ID that you received from your personal account</td></tr><tr><td>type</td><td>required</td><td>string</td><td>static</td><td>Type of your widget. It can be 'static' or 'fullscreen'</td></tr><tr><td>debug</td><td>optional</td><td>boolean</td><td>false</td><td>Flag which you can use for development mode (it doesn't collect data in your ads account and doesn't requests real ads)</td></tr><tr><td>onShowReward</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called after user watches ad</td></tr><tr><td>onClickReward</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called after user clicks ad</td></tr><tr><td>onAdsNotFound</td><td>optional</td><td>function</td><td>null</td><td>Callback which will be called if we don't find ads for user</td></tr></tbody></table>

##


---

# 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://tads.gitbook.io/docs/getting-started/publishers/embed-widget/vanilla-js.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.
