> [!NOTE]
> **Note:** Before moving forward with this guide, you must complete the steps in [Create the ads manager class](https://developers.google.com/ad-manager/dynamic-ad-insertion/sdk/html5/hbbtv-ads-manager.md.txt).

In `application.js`, create the main class for your HbbTV app that interacts
with the HbbTV broadcast. This class interacts with the `broadcastAppManager`
and `broadcastContainer`. For an example of a similar class, see
[Handling the broadcast a/v object](https://developer.hbbtv.org/tutorials/handling-the-broadcast-av-object/).

Modify this base HbbTV app to request an IMA stream and respond to ad break
events.

## Initialize the application

Initialize the application class in `application.js`, set up the
`broadcastAppManager`, and `broadcastContainer` following the tutorial,
[Handling the broadcast a/v object](https://developer.hbbtv.org/tutorials/handling-the-broadcast-av-object/).
Afterwards, initiate new `VideoPlayer` and `AdManager` objects.

```javascript
/** Main HbbTV Application. */
var HbbTVApp = function() {
  this.broadcastAppManager = document.getElementById('broadcast-app-manager');
  this.broadcastContainer = document.getElementById('broadcast-video');

  this.playState = -1; // -1 as null play state.

  try {
    this.applicationManager =
        this.broadcastAppManager.getOwnerApplication(document);
    this.applicationManager.show();
    this.broadcastContainer.bindToCurrentChannel();
    this.subscribedToStreamEvents = false;
    this.broadcastContainer.addEventListener(
        'PlayStateChange', this.onPlayStateChangeEvent.bind(this));

    debugView.log('HbbTVApp: App loaded');
    this.videoPlayer = new VideoPlayer();
    this.videoPlayer.setOnAdPodEnded(this.resumeBroadcast.bind(this));
  } catch (e) {
    debugView.log('HbbTVApp: No HbbTV device detected.');
    return;
  }

  this.adManager = new AdManager(this.videoPlayer);
};
```

## Make an IMA stream request

In the `HbbTVApp.onPlayStateChangeEvent()` method, make a stream request in
response to the app switching to the `PRESENTING_PLAYSTATE`. This approach
prepares your app to load the ad pod manifest in response to an
`AD_BREAK_EVENT_ANNOUNCE` event.

```javascript
if (!this.subscribedToStreamEvents &&
    this.broadcastContainer.playState == PRESENTING_PLAYSTATE) {
  this.subscribedToStreamEvents = true;
  this.broadcastContainer.addStreamEventListener(
      STREAM_EVENT_URL, 'eventItem', function(event) {
        this.onStreamEvent(event);
      }.bind(this));
  debugView.log('HbbTVApp: Subscribing to stream events.');
  this.adManager.requestStream(NETWORK_CODE, CUSTOM_ASSET_KEY);
}
```

If your device doesn't correctly emit the broadcast container `PlayStateChange`
event, use the `setInterval()` function to check for playstate changes:

```javascript
setInterval(function() {
      if (!subscribedToStreamEvents &&
            this.broadcastContainer.playState == PRESENTING_PLAYSTATE) {
        subscribedToStreamEvents = true;
        this.broadcastContainer.addStreamEventListener(
            STREAM_EVENT_URL, 'eventItem', function(event) {
              this.onStreamEvent(event);
            }.bind(this));
        debugView.log('Subscribing to stream events');
        this.adManager.requestStream(NETWORK_CODE, CUSTOM_ASSET_KEY);
      }
      ...
```

## Listen to HbbTV stream events

Create the `HbbTVApp.onStreamEvent()` method to listen to the ad break events
`adBreakAnnounce`, `adBreakStart`, and `adBreakEnd`:

```javascript
/**
 * Callback for HbbTV stream event.
 * @param {!Event} event Stream event payload.
 */
HbbTVApp.prototype.onStreamEvent = function(event) {
  var eventData = JSON.parse(event.text);
  var eventType = eventData.type;
  if (eventType == AD_BREAK_EVENT_ANNOUNCE) {
    this.onAdBreakAnnounce(eventData);
  } else if (eventType == AD_BREAK_EVENT_START) {
    this.onAdBreakStart(eventData);
  } else if (eventType == AD_BREAK_EVENT_END) {
    this.onAdBreakEnd(eventData);
  }
};
```

## Handle the HbbTV stream events

To handle the HbbTV stream events, complete the following steps:

1. To load the ad pod manifest in response to the `adBreakAnnounce` event,
   create the `HbbTVApp.onAdBreakAnnounce()` method:

   ```javascript
   /**
    * Callback function on ad break announce stream event.
    * @param {!Event} event HbbTV stream event payload.
    */
   HbbTVApp.prototype.onAdBreakAnnounce = function(event) {
     var eventType = event.type;
     var eventDuration = event.duration;
     var eventOffset = event.offset;
     debugView.log(
         'HbbTV event: ' + eventType + ' duration: ' + eventDuration +
         's offset: ' + eventOffset + 's');
     this.adManager.loadAdPodManifest(NETWORK_CODE, CUSTOM_ASSET_KEY, eventDuration);
   };
   ```
2. To switch to ad stream playback during ad breaks, create the
   `HbbTVApp.onAdBreakStart()` method:

   ```javascript
   /**
    * Callback function on ad break start stream event.
    * @param {!Event} event HbbTV stream event payload.
    */
   HbbTVApp.prototype.onAdBreakStart = function(event) {
     debugView.log('HbbTV event: ' + event.type);
     if (!this.videoPlayer.isPreloaded()) {
       debugView.log('HbbTVApp: Switch aborted. ' +
                     'The ad preloading buffer is insufficient.');
       return;
     }
     this.stopBroadcast();
     this.videoPlayer.play();
   };
   ```
3. To return to the content broadcast, create the `HbbTVApp.onAdBreakEnd()`
   method:

   ```javascript
   /**
    * Callback function on ad break end stream event.
    * @param {!Event} event HbbTV stream event payload.
    */
   HbbTVApp.prototype.onAdBreakEnd = function(event) {
     debugView.log('HbbTV event: ' + event.type);
     this.videoPlayer.stop();
     this.resumeBroadcast();
   };
   ```

You're now requesting and displaying IMA SDK ad pods in your HbbTV
app. To compare your app with a completed sample app, see the
[IMA HbbTV sample on GitHub](https://github.com/googleads/googleads-ima-html5-dai/tree/main/hbbtv).