Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.1 kB
2
Indexable
Never
import React, { useEffect, useRef, useState } from 'react';

const VideoPlayer = ({ adTagUrl }) => {
  const videoRef = useRef(null);
  const adContainerRef = useRef(null);
  const [adsManager, setAdsManager] = useState(null);
  const [adsLoader, setAdsLoader] = useState(null);

  useEffect(() => {
    // Only initialize the ad display container and request ads when the SDK is ready
    if (window.google && window.google.ima) {
      const adDisplayContainer = new window.google.ima.AdDisplayContainer(
        adContainerRef.current,
        videoRef.current
      );

      const adsLoader = new window.google.ima.AdsLoader(adDisplayContainer);
      setAdsLoader(adsLoader);

      adsLoader.addEventListener(
        window.google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
        onAdsManagerLoaded,
        false
      );
      adsLoader.addEventListener(
        window.google.ima.AdErrorEvent.Type.AD_ERROR,
        onAdError,
        false
      );

      const adsRequest = new window.google.ima.AdsRequest();
      adsRequest.adTagUrl = adTagUrl;

      // Must be done via a user action on mobile devices
      adDisplayContainer.initialize();
      videoRef.current.load();
      adsLoader.requestAds(adsRequest);
    }
  }, [adTagUrl]);

  const onAdsManagerLoaded = (event) => {
    const adsManager = event.getAdsManager(videoRef.current);
    setAdsManager(adsManager);
    adsManager.init(640, 360, window.google.ima.ViewMode.NORMAL);
    adsManager.start();
  };

  const onAdError = (error) => {
    console.error('Ad Error:', error.getError());
    adsManager && adsManager.destroy();
  };

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      adsLoader && adsLoader.destroy();
      adsManager && adsManager.destroy();
    };
  }, [adsLoader, adsManager]);

  return (
    <div>
      <div ref={adContainerRef} />
      <video ref={videoRef} controls>
        <source src="path_to_your_video.mp4" type="video/mp4" />
      </video>
    </div>
  );
};

export default VideoPlayer;
Leave a Comment