Skip to content

Code examples

For now, we have only rewarded ad format, which mean you should give user reward when he watched ad till the end and ad should be expected like after click on element.
More info about show ad requirements.

React

Create useAdsgram hook

Create file inside your project with custom hook useAdsgram.
More info about custom hooks in React documentation.

Also, you should insert this script inside <head> tag.

javascript
import { useCallback, useEffect, useRef } from 'react';

export function useAdsgram({ blockId, onReward, onError }) {
  const AdControllerRef = useRef(undefined);

  useEffect(() => {
    AdControllerRef.current = window.Adsgram?.init({ blockId });
  }, [blockId]);

  return useCallback(async () => {
    if (AdControllerRef.current) {
      AdControllerRef.current
        .show()
        .then(() => {
          // user watch ad till the end
          onReward();
        })
        .catch((result) => {
          // user get error during playing ad or skip ad
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}
typescript
import { useCallback, useEffect, useRef } from 'react';
/**
 * Check Typescript section
 * and use your path to adsgram types
 */
import type { AdController, ShowPromiseResult } from 'path-to-adsgram-types';

export interface useAdsgramParams {
  blockId: string;
  onReward: () => void;
  onError?: (result: ShowPromiseResult) => void;
}

export function useAdsgram({ blockId, onReward, onError }: useAdsgramParams): () => Promise<void> {
  const AdControllerRef = useRef<AdController | undefined>(undefined);

  useEffect(() => {
    AdControllerRef.current = window.Adsgram?.init({ blockId, debug: true, debugBannerType: 'FullscreenMedia' });
  }, [blockId]);

  return useCallback(async () => {
    if (AdControllerRef.current) {
      AdControllerRef.current
        .show()
        .then(() => {
          // user watch ad till the end
          onReward();
        })
        .catch((result: ShowPromiseResult) => {
          // user get error during playing ad or skip ad
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}

Usage example

Example of simple button component, when click on the button ad will be showed.

jsx
import { useCallback, ReactElement } from 'react'
import { useAdsgram } from "./hooks/useAdsgram.ts";


export function ShowAdButton() {
  const onReward = useCallback(() => {
    alert('Reward');
  }, []);
  const onError = useCallback((result) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

  /**
   * insert your-block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>Show Ad</button>
  )
}
tsx
import { useCallback, ReactElement } from 'react'
import { useAdsgram } from "./hooks/useAdsgram.ts";
import { ShowPromiseResult } from "./types/adsgram";


export function ShowAdButton(): ReactElement {
  const onReward = useCallback(() => {
    alert('Reward');
  }, []);
  const onError = useCallback((result: ShowPromiseResult) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

  /**
   * insert your-block-id
   */
  const showAd = useAdsgram({ blockId: "your-block-id", onReward, onError });

  return (
    <button onClick={showAd}>Show Ad</button>
  )
}

Unity

We don't have plugins for unity.

Create .jslib file, you can read more about it here.

You can call js functions from unity using this.
You can call unity functions from js using this.

Vanilla js

Example with inline script and button to show ad.

html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Test app</title>
        <script src="https://telegram.org/js/telegram-web-app.js"></script>
        <script src="https://sad.adsgram.ai/js/sad.min.js"></script>
    </head>
    <body>
        <button id="ad">Show ad</button>
        <script>
            // insert your block id
            const AdController = window.Adsgram.init({ blockId: "your-block-id" });
            const button = document.getElementById('ad');
            button.addEventListener('click', () => {
                AdController.show().then((result) => {
                    // user watch ad till the end
                    // your code to reward user
                    alert('Reward');
                }).catch((result) => {
                    // user skipped video or get error during playing ad
                    // do nothing or whatever you want
                    alert(JSON.stringify(result, null, 4));
                })
            })
        </script>
    </body>
</html>