Skip to content

代码示例

  • 奖励格式,这意味着当用户观看广告至结束时,你应该给予用户奖励,广告应该在点击元素后出现。
    有关显示广告要求的更多信息
  • 插页格式,这意味着用户可以在结束前跳过广告,广告应该在应用程序流程的自然暂停期间出现。
    有关显示广告要求的更多信息

信息

以下是奖励格式的代码示例。这些示例也适用于插页格式。唯一的区别在于,AdController.show()承诺会为已观看至结束的广告以及已关闭的广告解析。你可以在这里找到一个简单的示例。

React

插入脚本

将此脚本插入到你的HTML的<head>标签内

创建useAdsgram钩子

在你的项目中创建一个带有自定义钩子useAdsgram的文件。
有关React文档中自定义钩子的更多信息

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(() => {
          // 用户观看广告至结束或在插页格式中关闭它
          onReward();
        })
        .catch((result) => {
          // 用户在播放广告时遇到错误
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram脚本未加载',
      });
    }
  }, [onError, onReward]);
}
typescript
import { useCallback, useEffect, useRef } from 'react';
/**
 * 检查TypeScript部分
 * 并使用你到adsgram类型的路径
 */
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(() => {
          // 用户观看广告至结束或在插页格式中关闭它
          onReward?.();
        })
        .catch((result: ShowPromiseResult) => {
          // 用户在播放广告时遇到错误
          onError?.(result);
        });
    } else {
      onError?.({
        error: true,
        done: false,
        state: 'load',
        description: 'Adsgram script not loaded',
      });
    }
  }, [onError, onReward]);
}

使用示例

简单按钮组件的示例,当点击按钮时将显示广告。

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));
  }, []);

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

  return (
    <button onClick={showAd}>显示广告</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('奖励');
  }, []);
  const onError = useCallback((result: ShowPromiseResult) => {
    alert(JSON.stringify(result, null, 4));
  }, []);

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

  return (
    <button onClick={showAd}>显示广告</button>
  )
}

Unity

我们没有适用于Unity的插件。

创建.jslib文件,你可以在这里了解更多信息。

你可以基于这个方法从Unity调用JavaScript函数。
你可以基于这个方法从JavaScript调用Unity函数。

Vanilla js

inline 代码和按钮来显示广告

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>
            // 插入你的block-id
            const AdController = window.Adsgram.init({ blockId: "your-block-id" });
            const button = document.getElementById('ad');
            button.addEventListener('click', () => {
                AdController.show().then((result) => {
                    // 用户观看完整广告或在插屏模式下关闭广告
                    // 在奖励广告模式下执行奖励逻辑
                    alert('Reward');
                }).catch((result) => {
                    // 用户播放广告时发生错误
                    // 可选择不执行任何操作
                    alert(JSON.stringify(result, null, 4));
                })
            })
        </script>
    </body>
</html>