> 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/zh/jiao-cheng/fa-bu-shang-jiao-cheng/fpi-spa-with-exoclick.md).

# 单页应用中的全页插页广告

本指南演示如何实现 **整页插页广告（FPI）** 在单页应用（SPA）中使用直接 API 调用投放广告。适用于 React、Vue、Angular 以及其他框架。

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

## 分步实现

{% stepper %}
{% step %}

### 设置组件状态

首先，创建状态变量来跟踪你的广告系统和导航：

```typescript
'use client'

import { useEffect, useState } from 'react'

export default function HomePage() {
  const [adLoaded, setAdLoaded] = useState(false)
  const [currentPage, setCurrentPage] = useState('home')

  useEffect(() => {
    setAdLoaded(true)
    console.log('✅ FPI API 方法已初始化')
  }, [])
}
```

{% endstep %}

{% step %}

### 创建 API 请求函数

此函数会向 FPI 广告服务器发起直接 HTTP 请求：

```typescript
const triggerFPIAd = async () => {
  console.log('🎯 正在向 FPI 服务发起直接 API 调用...')

  try {
    // 准备包含用户上下文的请求
    const requestBody = {
      user: {
        ua: navigator.userAgent,
        language: navigator.language || 'en-US',
        referer: window.location.href,
        consumer: 'ad-provider',
        gdpr: { gdpr: 0 },
        screen_resolution: `${screen.width}x${screen.height}`,
        window_orientation: screen.width > screen.height ? 'landscape' : 'portrait',
        cookies: [],
        scr_info: btoa('async||3')
      },
      zones: [{
        custom_targeting: {},
        id: 1234567, // 你的 FPI 区域 ID（移动设备请使用移动端 FPI 区域 ID）
        extra_params: {
          first_request: true,
          zone_type: 35 // 插页格式
        }
      }]
    }

    // 发起 API 调用
    const response = await fetch('https://s.pemsrv.com/v1/api.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    console.log('📥 完整 API 响应：', data)

    // 处理响应
    if (data.zones && data.zones.length > 0) {
      const zone = data.zones[0]
     
      if (zone.data) {
        console.log('🎨 正在展示广告...')
        await displayInterstitialAd(zone.data)
      } else {
        console.log('❌ 响应中没有广告数据')
      }
    }

  } catch (error) {
    console.error('❌ FPI API 错误：', error)
  }
}
```

{% endstep %}

{% step %}

### 创建展示函数

此函数处理多种广告格式

```typescript
const displayInterstitialAd = async (adData: any) => {
  console.log('🎨 正在开始展示插页广告...')

  try {
    // 移除任何现有遮罩层
    const existingOverlay = document.getElementById('fpi-interstitial-overlay')
    if (existingOverlay) {
      document.body.removeChild(existingOverlay)
    }

    // 创建全屏遮罩层
    const overlay = document.createElement('div')
    overlay.id = 'fpi-interstitial-overlay'
    overlay.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-color: rgba(0, 0, 0, 0.9);
      z-index: 999999;
      display: flex;
      align-items: center;
      justify-content: center;
    `

    // 创建广告容器
    const adContainer = document.createElement('div')
    adContainer.style.cssText = `
      position: relative;
      width: 100vw;
      height: 100vh;
      background: white;
      overflow: hidden;
    `

    // 创建关闭按钮
    const closeButton = document.createElement('button')
    closeButton.innerHTML = '✕'
    closeButton.style.cssText = `
      position: absolute;
      top: 10px;
      right: 10px;
      width: 40px;
      height: 40px;
      border: none;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      font-size: 20px;
      border-radius: 50%;
      cursor: pointer;
      z-index: 1000000;
    `

    closeButton.onclick = () => {
      document.body.removeChild(overlay)
      console.log('🚪 插页广告已关闭')
    }

    // 确定广告格式并创建内容
    let adContent = ''

    // 格式 1：Iframe 广告
    if (adData.html && adData.html.includes('iframe.php')) {
      `
        <iframe
          src="${adData.html}"
          width="100%"
          height="100%"
          frameborder="0"
          allowfullscreen
          sandbox="allow-scripts allow-forms allow-popups"
          style="width: 100vw; height: 100vh; border: none;"
        ></iframe>
      `
      console.log('🖼️ 已创建 iframe 广告')
    }
```

<details>

<summary>点击展开其他广告格式</summary>

```typescript
    if (adData.html && adData.html.includes('iframe.php')) {
      `
        <iframe
          src="${adData.html}"
          width="100%"
          height="100%"
          frameborder="0"
          allowfullscreen
          sandbox="allow-scripts allow-forms allow-popups"
          style="width: 100vw; height: 100vh; border: none;"
        ></iframe>
      `
      console.log('🖼️ 已创建 iframe 广告')
    }
   
    // 格式 2：视频广告
    else if (adData.video) {
      const hasClickUrl = adData.url && adData.url.trim() !== ''

      if (hasClickUrl) {
        // 带点击跳转的视频
        `
          <div style="position: relative; width: 100vw; height: 100vh; cursor: pointer;"
               onclick="window.open('${adData.url}', '_blank')">
            <video
              width="100%"
              height="100%"
              autoplay
              muted
              loop
              style="object-fit: cover; width: 100vw; height: 100vh;"
            >
              <source src="${adData.video}" type="video/mp4">
            </video>
            <div style="
              position: absolute;
              bottom: 20px;
              left: 50%;
              transform: translateX(-50%);
              background: rgba(0, 0, 0, 0.7);
              color: white;
              padding: 8px 16px;
              border-radius: 20px;
              font-size: 14px;
            ">
              点击访问广告主
            </div>
          </div>
        `
        console.log('🎬 已创建可点击视频横幅广告')
      } else {
        // 普通视频
        `
          <video
            width="100%"
            height="100%"
            autoplay
            muted
            controls
            style="object-fit: cover; width: 100vw; height: 100vh;"
          >
            <source src="${adData.video}" type="video/mp4">
          </video>
        `
        console.log('🎬 已创建视频广告')
      }
    }
   
    // 格式 3：点击跳转广告
    else if (adData.url) {
      `
        <div style="
          width: 100vw;
          height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          background: linear-gradient(45deg, #0072ba, #28a745);
          padding: 20px;
        ">
          <h2 style="color: white; margin-bottom: 20px; font-size: 48px;">
            🎯 插页广告
          </h2>
          <p style="color: white; margin-bottom: 30px; font-size: 24px;">
            点击访问广告主
          </p>
          <a href="${adData.url}"
             target="_blank"
             style="
               padding: 15px 30px;
               background: white;
               color: #0072ba;
               text-decoration: none;
               border-radius: 25px;
               font-weight: bold;
               font-size: 18px;
             ">
            立即访问
          </a>
        </div>
      `
      console.log('🔗 已创建点击跳转广告')
    }
   
    // 格式 4：原生广告
    else if (adData.ad_items && adData.ad_items.length > 0) {
      const adItemsHtml = adData.ad_items.map((item: any) => `
        <div style="
          background: white;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          cursor: pointer;
        " onclick="window.open('${item.url}', '_blank')">
          <div style="height: 200px; overflow: hidden;">
            <img src="${item.optimum_image || item.image}"
                 style="width: 100%; height: 100%; object-fit: cover;"
                 alt="${item.title}">
          </div>
          <div style="padding: 15px;">
            <h3 style="margin: 0 0 8px 0; font-size: 18px;">${item.title}</h3>
            ${item.description ? `<p style="font-size: 14px; color: #666;">${item.description}</p>` : ''}
            <div style="font-size: 12px; color: #999;">${item.brand || '赞助'}</div>
          </div>
        </div>
      `).join('')

      `
        <div style="
          width: 100vw;
          height: 100vh;
          background: #f5f5f5;
          overflow-y: auto;
          padding: 20px;
        ">
          <h2 style="text-align: center; margin-bottom: 20px;">赞助内容</h2>
          <div style="
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
          ">
            ${adItemsHtml}
          </div>
        </div>
      `
      console.log('🎯 已创建原生广告网格')
    }

    // 将内容添加到容器
    adContainer.innerHTML = adContent
    adContainer.appendChild(closeButton)
    overlay.appendChild(adContainer)
    document.body.appendChild(overlay)

    // 跟踪展示次数
    if (adData.impression) {
      fetch(adData.impression, { method: 'GET', mode: 'no-cors' })
        .then(() => console.log('📊 已跟踪展示次数'))
        .catch(e => console.log('⚠️ 展示次数跟踪失败：', e))
    }

  } catch (error) {
    console.error('❌ 显示广告时出错：', error)
  }
}
```

</details>
{% endstep %}

{% step %}

### 添加触发按钮

```tsx
return (
  <div>
    <h1>我的页面</h1>
    <button onClick={triggerFPIAd}>
      加载 FPI 广告
    </button>
  </div>
)
```

{% endstep %}
{% endstepper %}

## 完整代码示例

准备好看看实际效果了吗？查看我们的交互式演示，它将上面的所有步骤组合成一个可运行的实现。

**在线演示：** [查看代码和演示站点](https://codesandbox.io/p/devbox/exo-spa-fpi-58zynm)

<figure><img src="/files/6139eea97371c90b29a6926410bba64c496f01e0" 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://docs.exoclick.com/tutorials/zh/jiao-cheng/fa-bu-shang-jiao-cheng/fpi-spa-with-exoclick.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.
