Skip to content

Incorporação de cartões de banner

Saiba como incorporar cartões de banner usando o Braze SDK, para que possa engajar os usuários com uma experiência que pareça natural. Para saber mais sobre informações gerais, consulte Sobre cartões de banner.

Pré-requisitos

Essas são as versões mínimas do SDK necessárias para começar a usar os cartões de banner:

Incorporação de um cartão de banner

Step 1: Create placements

If you haven’t already, you’ll need to create Banner placements in Braze that are used to define the locations in your app or site can display Banners. To create a placement, go to Settings > Banners Placements, then select Create Placement.

Banner Placements section to create placement IDs.

Give your placement a name and assign a Placement ID. Be sure you consult other teams before assigning an ID, as it’ll be used throughout the card’s lifecycle and shouldn’t be changed later. For more information, see Placement IDs.

Placement details that designate a Banner will display in the left sidebar for spring sale promotion campaigns.

Etapa 2: Atualize os canais em seu app

Os posicionamentos podem ser solicitados a cada sessão e serão armazenados em cache automaticamente quando a sessão de um usuário expirar ou quando você alterar os usuários identificados usando o método changeUser.

1
2
3
import * as braze from "@braze/web-sdk";

braze.requestBannersRefresh(["global_banner", "navigation_square_banner"])
1
AppDelegate.braze?.banners.requestRefresh(placementIds: ["global_banner", "navigation_square_banner"])
1
2
3
4
ArrayList<String> listOfBanners = new ArrayList<>();
listOfBanners.add("global_banner");
listOfBanners.add("navigation_square_banner");
Braze.getInstance(context).requestBannersRefresh(listOfBanners);
1
Braze.getInstance(context).requestBannersRefresh(listOf("global_banner", "navigation_square_banner"))
1
Braze.requestBannersRefresh(["global_banner", "navigation_square_banner"]);
1
This feature is not currently supported on Unity.
1
This feature is not currently supported on Cordova.
1
braze.requestBannersRefresh(["global_banner", "navigation_square_banner"]);
1
This feature is not currently supported on Roku.

Etapa 3: Ouça as atualizações

1
2
3
4
5
6
7
8
import * as braze from "@braze/web-sdk";

braze.subscribeToBannersUpdates((banners) => {
  console.log(`Banners were updated`);
})

// always refresh after your subscriber function has been registered
braze.requestBannersRefresh(["global_banner", "navigation_square_banner"])
1
2
3
4
5
let cancellable = brazeClient.braze()?.banners.subscribeToUpdates { banners in
  banners.forEach { placementId, banner in
    print("Received banner: \(banner) with placement ID: \(placementId)")
  }
}
1
2
3
4
5
Braze.getInstance(context).subscribeToBannersUpdates(banners -> {
  for (Banner banner : banners.getBanners()) {
    Log.d(TAG, "Received banner: " + banner.getPlacementId());
  }
});
1
2
3
4
5
Braze.getInstance(context).subscribeToBannersUpdates { update ->
  for (banner in update.banners) {
    Log.d(TAG, "Received banner: " + banner.placementId)
  }
}
1
2
3
4
5
6
7
8
9
10
const bannerCardsSubscription = Braze.addListener(
  Braze.Events.BANNER_CARDS_UPDATED,
  data => {
    const banners = data.banners;
    console.log(
      `Received ${banners.length} Banner Cards with placement IDs:`,
      banners.map(banner => banner.placementId),
    );
  },
);
1
This feature is not currently supported on Unity.
1
This feature is not currently supported on Cordova.
1
2
3
4
5
StreamSubscription bannerStreamSubscription = braze.subscribeToBanners((List<BrazeBanner> banners) {
  for (final banner in banners) {
    print("Received banner: " + banner.toString());
  }
});
1
This feature is not currently supported on Roku.

Etapa 4: Incorporar usando a ID de colocação

Crie um elemento de contêiner para o banner. Não se esqueça de definir sua largura e altura.

1
<div id="global-banner-container" style="width: 100%; height: 450px;"></div>

Em seguida, use o método insertBanner para substituir o HTML interno do elemento contêiner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import * as braze from "@braze/web-sdk";

braze.initialize("sdk-api-key", {
    baseUrl: "sdk-base-url",
    allowUserSuppliedJavascript: true, // banners require you to opt-in to user-supplied javascript
});

braze.subscribeToBannersUpdates((banners) => {
   
    // get this placement's banner. If it's `null` the user did not qualify for one.
    const globalBanner = braze.getBanner("global_banner");
    if (!globalBanner) {
        return;
    }

    // choose where in the DOM you want to insert the banner HTML
    const container = document.getElementById("global-banner-container");

    // Insert the banner which replacees the innerHTML of that container
    braze.insertBanner(globalBanner, container);

    // Special handling if the user is part of a Control Variant
    if (globalBanner.isControl) {
        // hide or collapse the container
        container.style.display = 'none';
    }
});

braze.requestBannersRefresh(["global_banner", "navigation_square_banner"])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// To get access to the Banner model object:
let globalBanner: Braze.Banner?
AppDelegate.braze?.banners.getBanner(for: "global_banner", { banner in
  self.globalBanner = banner
})

// If you simply want the Banner view, you may initialize a `UIView` with the placement ID:
if let braze = AppDelegate.braze {
  let bannerUIView = BrazeBannerUI.BannerUIView(
    placementId: "global_banner",
    braze: braze,
    // iOS does not perform automatic resizing or visibility changes.
    // Use the `processContentUpdates` parameter to adjust the size and visibility of your Banner Card according to your use case.
    processContentUpdates: { result in
      switch result {
      case .success(let updates):
        if let height = updates.height {
          // Adjust the visibility and/or height.
        }
      case .failure(let error):
        // Handle the error.
      }
    }
  )
}

// Similarly, if you want a Banner view in SwiftUI, use the corresponding `BannerView` initializer:
if let braze = AppDelegate.braze {
  let bannerView = BrazeBannerUI.BannerView(
    placementId: "global_banner",
    braze: braze,
    // iOS does not perform automatic resizing or visibility changes.
    // Use the `processContentUpdates` parameter to adjust the size and visibility of your Banner Card according to your use case.
    processContentUpdates: { result in
      switch result {
      case .success(let updates):
        if let height = updates.height {
          // Adjust the visibility and/or height according to your parent controller.
        }
      case .failure(let error):
        // Handle the error.
      }
    }
  )
}

Para obter o banner no código Java, use:

1
Banner globalBanner = Braze.getInstance(context).getBanner("global_banner");

Você pode criar cartões de banner em seu layout de visualizações do Android incluindo esse XML:

1
2
3
4
5
<com.braze.ui.banners.BannerView
    android:id="@+id/global_banner_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:placementId="global_banner" />

Para obter o banner em Kotlin, use:

1
val banner = Braze.getInstance(context).getBanner("global_banner")

Se estiver usando o Android Views, use este XML:

1
2
3
4
5
<com.braze.ui.banners.BannerView
    android:id="@+id/global_banner_id"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:placementId="global_banner" />

Se estiver usando o Jetpack Compose, poderá usar isso:

1
Banner(placementId = "global_banner")

Se estiver usando a Nova Arquitetura do React Native, será necessário registrar BrazeBannerView como um componente Fabric em seu site AppDelegate.mm.

1
2
3
4
5
6
7
8
#ifdef RCT_NEW_ARCH_ENABLED
/// Register the `BrazeBannerView` for use as a Fabric component.
- (NSDictionary<NSString *,Class<RCTComponentViewProtocol>> *)thirdPartyFabricComponents {
  NSMutableDictionary * dictionary = [super thirdPartyFabricComponents].mutableCopy;
  dictionary[@"BrazeBannerView"] = [BrazeBannerView class];
  return dictionary;
}
#endif

Para obter o modelo de dados do cartão de banner no React Native, use:

1
const banner = await Braze.getBanner("global_banner");

Você pode usar o método getBanner para verificar a presença desse posicionamento no cache do usuário. No entanto, para obter a integração mais simples, adicione o seguinte trecho de JavaScript XML (JSX) à hierarquia da visualização, fornecendo apenas o ID do posicionamento.

1
2
3
<Braze.BrazeBannerView
  placementID='global_banner'
/>
1
This feature is not currently supported on Unity.
1
This feature is not currently supported on Cordova.

Para obter o modelo de dados do cartão de banner no Flutter, use:

1
2
3
4
5
6
7
braze.getBanner("global_banner").then((banner) {
  if (banner == null) {
    // Handle null cases.
  } else {
    print(banner.toString());
  }
});

Você pode usar o método getBanner para verificar a presença desse posicionamento no cache do usuário. No entanto, para obter a integração mais simples, adicione o seguinte widget à hierarquia da visualização, fornecendo apenas o ID do posicionamento.

1
2
3
BrazeBannerView(
  placementId: "global_banner",
),
1
This feature is not currently supported on Roku.

Etapa 5: Enviar um cartão de teste (opcional)

Antes de lançar uma campanha de cartão de banner, você pode enviar um cartão de banner de teste para verificar a integração. Os cartões de teste serão armazenados em um cache separado na memória e não persistirão entre as reinicializações do app. Embora não seja necessária nenhuma configuração extra, seu dispositivo de teste deve ser capaz de receber notificações por push em primeiro plano para que possa exibir o cartão de teste.

Análise de dados de registro

O Braze registra automaticamente as impressões quando você usa os métodos do SDK para inserir um cartão de banner - portanto, não há necessidade de rastrear as impressões manualmente. Se precisar analisar e renderizar o HTML em uma exibição personalizada, entre em contato conosco pelo e-mail [email protected].

Dimensões e dimensionamento

Aqui estão algumas coisas que você deve saber sobre as dimensões e o tamanho do cartão de banner:

  • Embora o criador permita a prévia de banners em diferentes dimensões, essas informações não são salvas nem enviadas ao SDK.
  • O HTML ocupará toda a largura do contêiner em que for renderizado.
  • Recomendamos criar um elemento de dimensão fixa e testar essas dimensões no criador.
QUÃO ÚTIL FOI ESTA PÁGINA?
New Stuff!