> 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/fr/tutoriels/tutoriels-editeurs/fpi-spa-with-exoclick.md).

# Publicités interstitielles plein écran dans les applications monopage

Ce guide démontre comment implémenter **une interstitielle plein écran (FPI)** des publicités dans une application monopage (SPA) à l’aide d’appels API directs. Fonctionne avec React, Vue, Angular et d’autres frameworks.

<figure><img src="/files/6e7db6f83cebd49f546703adc95ca3dbbdb947bf" alt=""><figcaption></figcaption></figure>

## Implémentation étape par étape

{% stepper %}
{% step %}

### Configurer l’état du composant

Tout d’abord, créez des variables d’état pour suivre votre système publicitaire et la navigation :

```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('✅ Méthode API FPI initialisée')
  }, [])
}
```

{% endstep %}

{% step %}

### Créer la fonction de requête API

Cette fonction effectue une requête HTTP directe vers le serveur publicitaire FPI :

```typescript
const triggerFPIAd = async () => {
  console.log('🎯 Appel API direct au service FPI...')

  try {
    // Préparer la requête avec le contexte utilisateur
    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, // Votre ID de zone FPI (utilisez l’ID de zone FPI mobile pour les appareils mobiles)
        extra_params: {
          first_request: true,
          zone_type: 35 // Format interstitiel
        }
      }]
    }

    // Effectuer l’appel 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(`Erreur HTTP ! statut : ${response.status}`)
    }

    const data = await response.json()
    console.log('📥 Réponse API complète :', data)

    // Traiter la réponse
    if (data.zones && data.zones.length > 0) {
      const zone = data.zones[0]
     
      if (zone.data) {
        console.log('🎨 Affichage de la publicité...')
        await displayInterstitialAd(zone.data)
      } else {
        console.log('❌ Aucune donnée publicitaire dans la réponse')
      }
    }

  } catch (error) {
    console.error('❌ Erreur API FPI :', error)
  }
}
```

{% endstep %}

{% step %}

### Créer la fonction d’affichage

Cette fonction gère plusieurs formats publicitaires

```typescript
const displayInterstitialAd = async (adData: any) => {
  console.log('🎨 Début de l’affichage de la publicité interstitielle...')

  try {
    // Supprimer tout overlay existant
    const existingOverlay = document.getElementById('fpi-interstitial-overlay')
    if (existingOverlay) {
      document.body.removeChild(existingOverlay)
    }

    // Créer un overlay plein écran
    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;
    `

    // Créer le conteneur de la publicité
    const adContainer = document.createElement('div')
    adContainer.style.cssText = `
      position: relative;
      width: 100vw;
      height: 100vh;
      background: white;
      overflow: hidden;
    `

    // Créer le bouton de fermeture
    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('🚪 Publicité interstitielle fermée')
    }

    // Déterminer le format de la publicité et créer le contenu
    let adContent = ''

    // Format 1 : publicité iframe
    if (adData.html && adData.html.includes('iframe.php')) {
      adContent = `
        <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('🖼️ Publicité iframe créée')
    }
```

<details>

<summary>Cliquez pour développer des formats publicitaires supplémentaires</summary>

```typescript
    if (adData.html && adData.html.includes('iframe.php')) {
      adContent = `
        <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('🖼️ Publicité iframe créée')
    }
   
    // Format 2 : publicité vidéo
    else if (adData.video) {
      const hasClickUrl = adData.url && adData.url.trim() !== ''

      if (hasClickUrl) {
        // Vidéo avec clic
        adContent = `
          <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;
            ">
              Cliquez pour visiter l’annonceur
            </div>
          </div>
        `
        console.log('🎬 Bannière vidéo cliquable créée')
      } else {
        // Vidéo standard
        adContent = `
          <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('🎬 Publicité vidéo créée')
      }
    }
   
    // Format 3 : publicité avec clic
    else if (adData.url) {
      adContent = `
        <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;">
            🎯 Publicité interstitielle
          </h2>
          <p style="color: white; margin-bottom: 30px; font-size: 24px;">
            Cliquez pour visiter l’annonceur
          </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;
             ">
            Visitez maintenant
          </a>
        </div>
      `
      console.log('🔗 Publicité avec clic créée')
    }
   
    // Format 4 : publicités natives
    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 || 'Sponsorisé'}</div>
          </div>
        </div>
      `).join('')

      adContent = `
        <div style="
          width: 100vw;
          height: 100vh;
          background: #f5f5f5;
          overflow-y: auto;
          padding: 20px;
        ">
          <h2 style="text-align: center; margin-bottom: 20px;">Contenu sponsorisé</h2>
          <div style="
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
          ">
            ${adItemsHtml}
          </div>
        </div>
      `
      console.log('🎯 Grille de publicité native créée')
    }

    // Ajouter le contenu au conteneur
    adContainer.innerHTML = adContent
    adContainer.appendChild(closeButton)
    overlay.appendChild(adContainer)
    document.body.appendChild(overlay)

    // Suivre l’impression
    if (adData.impression) {
      fetch(adData.impression, { method: 'GET', mode: 'no-cors' })
        .then(() => console.log('📊 Impression suivie'))
        .catch(e => console.log('⚠️ Échec du suivi de l’impression :', e))
    }

  } catch (error) {
    console.error('❌ Erreur lors de l’affichage de la publicité :', error)
  }
}
```

</details>
{% endstep %}

{% step %}

### Ajouter le bouton de déclenchement

```tsx
return (
  <div>
    <h1>Ma page</h1>
    <button onClick={triggerFPIAd}>
      Charger la publicité FPI
    </button>
  </div>
)
```

{% endstep %}
{% endstepper %}

## Exemple de code complet

Prêt à le voir en action ? Découvrez notre démo interactive qui combine toutes les étapes ci-dessus en une implémentation fonctionnelle.

**Démo en direct :** [Voir le code et le site de démonstration](https://codesandbox.io/p/devbox/exo-spa-fpi-58zynm)

<figure><img src="/files/5f771b9a31ff42d1835afcda6c06f8908731a5cf" 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/fr/tutoriels/tutoriels-editeurs/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.
