Logo

Player Integration

The Playgent Player allows you to embed interactive games on any website with just a few lines of code. This guide covers all configuration options and integration methods.

Quick Start

1. Include the Script

<script src="https://static.playgent.com/player.js"></script>

2. Add a Container Element

<div id="playgent-player"></div>

3. Initialize the Player

const player = Playgent.init({
  containerId: "playgent-player",
  contentId: "your-content-id",
});

Installation Methods

Method 1: Programmatic API

For full control over the player lifecycle:

const player = Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  width: "100%",
  height: "600px",
  backgroundColor: "#1a1a2e",
  onGameCompleted: (data) => {
    console.log("Game completed!", data);
  },
});

Method 2: Data Attributes (Zero-JS)

For simple integrations without writing JavaScript:

<script
  src="https://static.playgent.com/player.js"
  data-playgent-player
  data-content-id="abc123"
  data-background-color="#1a1a2e"
  data-disable-leaderboards="true"
></script>

A container element is automatically created after the script tag.


Configuration Reference

Core Options

OptionTypeDefaultDescription
containerIdstring'playgent-player'ID of the DOM element to mount the player
contentIdstringRequired (unless using auto-gen). The unique identifier for the game content
widthstring'100%'Width of the player iframe (CSS value)
heightstring'400px'Height of the player iframe (CSS value)
maxWidthstring''Maximum width constraint (CSS value)
maxHeightstring''Maximum height constraint (CSS value)

Theming Options

Customize the appearance of the player to match your brand.

OptionTypeDefaultDescription
backgroundColorstringBackground color of the game (hex, e.g., '#1a1a2e')
fontstringFont family for game text (e.g., 'Roboto', 'Open Sans')

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  backgroundColor: "#0f0f23",
  font: "Poppins",
});

Play Button Customization

Style the play button on the game's cover screen.

OptionTypeDefaultDescription
playButtonBackgroundColorstringBackground color of the play button (hex)
playButtonTextColorstringText color of the play button (hex)
playButtonTextstringCustom text for the play button
hideIconbooleanfalseHide the game icon on the cover screen
iconUrlstringCustom icon URL for the cover screen

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  playButtonBackgroundColor: "#ff6b6b",
  playButtonTextColor: "#ffffff",
  playButtonText: "Start Challenge",
  iconUrl: "https://example.com/my-icon.png",
});

Feature Toggles

Enable or disable specific player features.

OptionTypeDefaultDescription
disableLeaderboardsbooleanfalseDisable the leaderboard feature
disableStatisticsbooleanfalseDisable game statistics tracking
hidePlaygentLogobooleanfalseHide the Playgent branding logo
languagestringForce a specific language (e.g., 'en', 'es', 'fr')
shareUrlstringCustom URL for the share functionality

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  disableLeaderboards: true,
  language: "es",
  shareUrl: "https://example.com/play/my-game",
});

End Screen Customization

Customize what users see when they complete a game.

OptionTypeDefaultDescription
endScreenTitlestringCustom title for the end screen
endScreenTextstringCustom message on the end screen
endScreenUrlstringURL to navigate when CTA button is clicked
endScreenButtonTextstringText for the CTA button on end screen

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  endScreenTitle: "Great Job!",
  endScreenText: "You completed the daily challenge",
  endScreenUrl: "https://example.com/subscribe",
  endScreenButtonText: "Subscribe for More",
});

Auto-Play Next

Configure automatic progression to the next game.

OptionTypeDefaultDescription
autoPlayNextbooleanEnable/disable auto-play next game feature
autoPlayNextSecondsnumberCountdown seconds before auto-playing next game

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  autoPlayNext: true,
  autoPlayNextSeconds: 5,
});

Advertising

Monetize your games with video ads.

OptionTypeDefaultDescription
preRollAdTagstringVAST/VPAID ad tag URL for pre-roll ads
rewardedAdTagstringVAST/VPAID ad tag URL for rewarded ads

Example

Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",
  preRollAdTag: "https://ads.example.com/vast?type=preroll",
  rewardedAdTag: "https://ads.example.com/vast?type=rewarded",
});

Auto-Generation Mode

Generate games automatically from your page content.

OptionTypeDefaultDescription
enableAutoGenbooleanfalseEnable auto-generation from page content
autoGenSelectorsstring[]['main', 'article', '.content']CSS selectors to extract content from
autoGenExcludeSelectorsstring[][]CSS selectors to exclude from extraction
autoGenGameTypesstring[][]Preferred game types to generate

Example

Playgent.init({
  containerId: "playgent-player",
  enableAutoGen: true,
  autoGenSelectors: ["article", ".post-content"],
  autoGenExcludeSelectors: [".sidebar", ".ads", ".comments"],
  autoGenGameTypes: ["trivia", "quiz"],
});

Note: When enableAutoGen is true, you don't need to provide a contentId. The player will automatically extract content from your page and generate a unique game.

Event Callbacks

Subscribe to game lifecycle events to integrate with your application.

Available Events

EventCallbackDescription
onGameView(data) => voidFired when the game cover screen is displayed
onGameInView(data) => voidFired when the player becomes visible in viewport
onGameStarted(data) => voidFired when the user starts playing
onGameCompleted(data) => voidFired when the game is completed

Event Data Objects

onGameView / onGameStarted

{
  contentId: string;
  gameType: string;
  title: string;
}

onGameInView

{
  type: "playgent_game_in_view";
  contentId: string;
  url: string;
  intersectionRatio: number;
}

onGameCompleted

{
  contentId: string;
  gameType: string;
  title: string;
  score: number;
  durationSeconds: number;
}

Example: Tracking Game Events

const player = Playgent.init({
  containerId: "playgent-player",
  contentId: "abc123",

  onGameView: (data) => {
    console.log("Game loaded:", data.title);
    analytics.track("game_view", { game: data.gameType });
  },

  onGameStarted: (data) => {
    console.log("User started playing:", data.title);
    analytics.track("game_start", { game: data.gameType });
  },

  onGameCompleted: (data) => {
    console.log(
      `Game completed! Score: ${data.score}, Time: ${data.durationSeconds}s`
    );
    analytics.track("game_complete", {
      game: data.gameType,
      score: data.score,
      duration: data.durationSeconds,
    });
  },
});

DOM Events

You can also listen for events on the window object:

window.addEventListener("playgent_game_in_view", (event) => {
  console.log("Player in view:", event.detail);
});

postMessage events (PG_*)

In addition to the callback API above, Playgent also emits PG_* lifecycle events via window.postMessage (useful for paywalls/login walls, analytics, and custom UI).

// 1) Create the embed
const player = Playgent.init({
  containerId: "playgent-player",
  contentId: "your-content-id",
});

// 2) Trust only messages from this iframe + origin
const playgentOrigin = new URL(player.iframe.src).origin;

window.addEventListener("message", (event) => {
  if (event.origin !== playgentOrigin) return;
  if (event.source !== player.iframe.contentWindow) return;

  const data = event.data || {};
  switch (data.type) {
    case "PG_GAME_VIEW":
      break;
    case "PG_GAME_STARTED":
      break;
    case "PG_GAME_COMPLETED":
      console.log("Score:", data.score);
      console.log("Duration (seconds):", data.duration_seconds);
      break;
  }
});

Supported events

  • PG_GAME_VIEW
  • PG_GAME_STARTED (sent once per session)
  • PG_GAME_COMPLETED (includes score, duration_seconds, and sometimes won)

Common payload fields

All PG_* events include:

  • type / event_name
  • publish_key
  • user_id / user_name (if you provide identity; see player/identity)
  • game_name, title
  • created_at, timestamp

Player Instance API

The Playgent.init() method returns a player instance with the following methods:

play(options)

Load and play different content without recreating the player.

player.play({
  contentId: "new-content-id",
  backgroundColor: "#2d3436",
});

on(eventName, callback)

Add event listeners after initialization.

player.on("gameCompleted", (data) => {
  showConfetti();
});

player.on("gameStarted", (data) => {
  pauseBackgroundMusic();
});

Available event names: gameView, gameInView, gameStarted, gameCompleted

off(eventName)

Remove an event listener.

player.off("gameCompleted");

destroy()

Clean up the player and remove it from the DOM.

player.destroy();

iframe

Direct access to the iframe element for advanced customization.

player.iframe.style.borderRadius = "20px";

Data Attributes Reference

When using the zero-JS data attribute method, convert camelCase options to kebab-case with a data- prefix.

JavaScript OptionData Attribute
contentIddata-content-id
containerIddata-container-id
backgroundColordata-background-color
fontdata-font
playButtonBackgroundColordata-play-button-background-color
playButtonTextColordata-play-button-text-color
playButtonTextdata-play-button-text
hideIcondata-hide-icon
iconUrldata-icon-url
disableLeaderboardsdata-disable-leaderboards
disableStatisticsdata-disable-statistics
hidePlaygentLogodata-hide-playgent-logo
languagedata-language
shareUrldata-share-url
preRollAdTagdata-pre-roll-ad-tag
rewardedAdTagdata-rewarded-ad-tag
endScreenTitledata-end-screen-title
endScreenTextdata-end-screen-text
endScreenUrldata-end-screen-url
endScreenButtonTextdata-end-screen-button-text
autoPlayNextdata-auto-play-next
autoPlayNextSecondsdata-auto-play-next-seconds
enableAutoGendata-enable-auto-gen
autoGenSelectorsdata-auto-gen-selectors
autoGenExcludeSelectorsdata-auto-gen-exclude-selectors
autoGenGameTypesdata-auto-gen-game-types
viewOncedata-view-once
viewThresholddata-view-threshold

Array Attributes

For array options, use comma-separated values:

<script
  src="https://static.playgent.com/player.js"
  data-playgent-player
  data-enable-auto-gen="true"
  data-auto-gen-selectors="article, .post-body, main"
  data-auto-gen-exclude-selectors=".sidebar, .comments, .ads"
  data-auto-gen-game-types="trivia, quiz, wordgame"
></script>

Complete Examples

Basic Embed

<!DOCTYPE html>
<html>
  <head>
    <title>My Game Page</title>
  </head>
  <body>
    <div id="game-container"></div>

    <script src="https://static.playgent.com/player.js"></script>
    <script>
      Playgent.init({
        containerId: "game-container",
        contentId: "daily-trivia-2024",
        width: "100%",
        height: "500px",
      });
    </script>
  </body>
</html>

Branded Experience

const player = Playgent.init({
  containerId: "playgent-player",
  contentId: "weekly-puzzle",

  // Branding
  backgroundColor: "#1a1a2e",
  font: "Montserrat",
  playButtonBackgroundColor: "#e94560",
  playButtonTextColor: "#ffffff",
  playButtonText: "Play Now",
  hidePlaygentLogo: true,

  // Features
  disableLeaderboards: false,
  language: "en",

  // End screen CTA
  endScreenTitle: "Nice Work!",
  endScreenText: "Come back tomorrow for a new challenge",
  endScreenUrl: "https://example.com/newsletter",
  endScreenButtonText: "Get Daily Games",
});

Auto-Generated Game from Article

<article class="blog-post">
  <h1>The History of Coffee</h1>
  <p>Coffee is one of the world's most popular beverages...</p>
  <!-- Article content -->
</article>

<div id="article-quiz"></div>

<script src="https://static.playgent.com/player.js"></script>
<script>
  Playgent.init({
    containerId: "article-quiz",
    enableAutoGen: true,
    autoGenSelectors: ["article.blog-post"],
    autoGenExcludeSelectors: [".author-bio", ".related-posts"],
    autoGenGameTypes: ["trivia"],

    onGameCompleted: (data) => {
      if (data.score >= 80) {
        showBadge("Coffee Expert");
      }
    },
  });
</script>

Multiple Players on One Page

// Player 1 - Daily Trivia
const triviaPlayer = Playgent.init({
  containerId: "trivia-container",
  contentId: "daily-trivia",
  height: "400px",
});

// Player 2 - Word Game
const wordPlayer = Playgent.init({
  containerId: "word-container",
  contentId: "daily-word",
  height: "500px",
});

// Switch trivia to a different game
document.getElementById("play-sports").addEventListener("click", () => {
  triviaPlayer.play({ contentId: "sports-trivia" });
});

React Integration

import { useEffect, useRef } from "react";

function PlaygentGame({ contentId, onComplete }) {
  const containerRef = useRef(null);
  const playerRef = useRef(null);

  useEffect(() => {
    if (!containerRef.current) return;

    playerRef.current = window.Playgent.init({
      containerId: containerRef.current.id,
      contentId,
      onGameCompleted: onComplete,
    });

    return () => {
      playerRef.current?.destroy();
    };
  }, [contentId, onComplete]);

  return <div id={`playgent-${contentId}`} ref={containerRef} />;
}

export default PlaygentGame;

Browser Support

The Playgent Player supports all modern browsers:

  • Chrome 60+
  • Firefox 55+
  • Safari 12+
  • Edge 79+
  • Mobile Safari (iOS 12+)
  • Chrome for Android

Touch Device Features

On mobile devices, the player automatically:

  • Enables swipe-to-scroll passthrough for vertical scrolling
  • Handles touch gestures appropriately
  • Maintains smooth scrolling while the player is in view

Troubleshooting

Player Not Appearing

  1. Verify the container element exists in the DOM before calling init()
  2. Check the browser console for error messages
  3. Ensure contentId is valid or enableAutoGen is set to true

Events Not Firing

  1. Verify callback functions are properly defined
  2. Check that the player iframe has loaded (events fire after load)
  3. Use player.on() to add listeners after initialization if needed

Styling Issues

  1. The iframe has default styles (border-radius: 10px, border: 1px solid #d7d9e4)
  2. Access player.iframe to override styles directly
  3. Use maxWidth and maxHeight to constrain dimensions

Legacy Compatibility

For backward compatibility, PlaygentPlayer is also available as an alias:

// Both work identically
window.Playgent.init(config);
window.PlaygentPlayer.init(config);