Basic integration with Compose
Android Web - Basic Integration with Compose
This page presumes that you are using Jetpack Compose.
Sample App
While reading the documentation, take a look at our Sample App.
This integration requires you to connect JavaScript code (in your web content) with Kotlin code (in your Android app).
Initialize Taboola
The initialization steps in this section are the same for Classic and Web integrations.
- Create a
TBLPublisherInfo
object and initialize Taboola:
val publisherInfo = TBLPublisherInfo("publisher-id")
// (Optional) Set the desired log level:
Taboola.setLogLevel(logLevel)
Taboola.init(publisherInfo)
Params
publisher-id
- a unique, machine-readable string (without spaces), as provided by Taboola.E.g.
"<<publisherID>>"
IMPORTANT
- Initialization is required once per application. It should be done as early as possible - preferably in a subclass of
Application
.- Failure to initialize successfully will result in Taboola recommendations not being displayed. Make sure that all paths within your application logic result in a successful initialization.
Build Taboola content instances
Guidelines
- The goal is to wrap your
WebView
with Taboola services.- For each page, initialize 1
TBLWebPage
instance, and create 1TBLWebUnit
instance only.- Use
AndroidView
to integrate theWebView
within your Compose UI.The steps below presume that you are using a
ViewModel
to manage theWebView
,TBLWebPage
andTBLWebUnit
state.
- Create a
ViewModel
, for example:
class TaboolaWebWrapperViewModel : ViewModel() {
}
Inside your ViewModel
:
- Obtain a Taboola Web Page instance:
val tblWebPage: TBLWebPage = Taboola.getWebPage()
- Build a Taboola Unit instance, for that Web Page:
val tblWebUnit: TBLWebUnit = tblWebPage.build(<yourWebView>, object : TBLWebListener() {})
For more detail about
TBLWebListener
, see: Advanced Options.
- Obtain a
WebSettings
instance for yourWebView
, and add the following settings:
val settings: WebSettings = <yourWebView>.settings
settings.javaScriptEnabled = true
// (Optional) Enable WebView debugging in your 'debug' builds.
// This makes debugging easier for any issues related to WebViews.
// See: https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true)
}
A sample code snippet for Steps 2 - 4:
/**
* Build a Taboola Page and Unit to describe the screen and placement you wish Taboola to work with.
* Notice: Taboola requires JavaScript to be enabled in the WebView to work.
*/
@SuppressLint("SetJavaScriptEnabled")
fun setupWebViewForTaboola(webView: WebView): TBLWebUnit {
// If not already set in your WebView
webView.settings.javaScriptEnabled = true
return Taboola.getWebPage().build(webView, object : TBLWebListener() {
override fun onItemClick(
placementName: String?,
itemId: String?,
clickUrl: String?,
isOrganic: Boolean,
customData: String?
): Boolean {
println("Taboola | onItemClick | isOrganic = $isOrganic")
return super.onItemClick(placementName, itemId, clickUrl, isOrganic, customData)
}
})
}
- Create a method to load web content within your
ViewModel
(You will call this method inside your@Composable
function after creating an instance of yourViewModel
):
/**
* This method is just a quick way to load an example page simulating customer layout.
* Inside the asset file there are Javascript tags Taboola targets with its content.
*/
fun loadWebViewContent(webView: WebView, placementInfo: PlacementInfo, context: Context) {
val baseUrl = "https://example.com"
val htmlContentFileName = "sampleContentPage.html"
var htmlContent: String? = null
try {
htmlContent = AssetUtil.getHtmlTemplateFileContent(context, htmlContentFileName)
htmlContent = htmlContent.replace("<PLACEMENT>", placementInfo.placementName)
htmlContent = htmlContent.replace("<MODE>", placementInfo.mode)
webView.loadDataWithBaseURL(baseUrl, htmlContent, "text/html", "UTF-8", "")
} catch (e: Exception) {
println("Failed to read asset file: ${e.localizedMessage}")
e.printStackTrace()
}
}
- Once you have created the single
TBLWebUnit
instance, your integration is ready to be passed to your@Composable
function by passing yourViewModel
and calling theViewModel
functions. The rest of the work is done by the JS tags.
If you are using
HorizontalPager
, see: Advanced Options
An integration example
@Composable
fun TaboolaWebScreen(placementInfo: PlacementInfo) {
val context = LocalContext.current
val viewModel: TaboolaWebWrapperViewModel = viewModel()
AndroidView(
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Set up the Taboola integration
viewModel.setupWebViewForTaboola(this)
viewModel.loadWebViewContent(this, placementInfo, context)
}
},
modifier = Modifier.fillMaxSize()
)
}
WebView
If you use
loadDataWithBaseURL()
, make sure to set a base URL.
Flow
If you load content within your own
WebView
- and then register it with the TaboolaWebView
- make sure to refresh its content.
A complete example
For a full, working implementation, see WebComposeWidgetFragment.kt and TaboolaWebWrapperViewModel.kt in our sample app.
The Click Event
Each time you build a TBLWebUnit
, you pass a subclass of TBLWebListener
that listens for events.
If desired, you can use this listener object to intercept the item click event, and open organic content directly within your app:
// In your ViewModel
fun setupWebViewForTaboola(webView: WebView): TBLWebUnit {
webView.settings.javaScriptEnabled = true
tblWebPage = Taboola.getWebPage()
tblWebUnit = tblWebPage?.build(webView, object : TBLWebListener() {
override fun onItemClick(
placementName: String?,
itemId: String?,
clickUrl: String?,
isOrganic: Boolean,
customData: String?
): Boolean {
// Insert your code here...
// Return 'false' if you are handling the click event yourself,
// or 'true' if you want Taboola SDK to handle the click event.
// Note: you can override the default behavior for *organic* content only.
return if (isOrganic) {
// Handle organic clicks in your app
navigateToArticle(clickUrl)
false
} else {
true
}
}
})
return tblWebUnit!!
}
private fun navigateToArticle(clickUrl: String?) {
// Implement your navigation logic here
// e.g., use Navigation Compose to navigate to article screen
}
You can override the default behavior for organic content only
For more information, see Event Handling and onItemClick.
Well Done!
You have completed the basic Compose integration steps!
If everything is working smoothly, take a look at the What's Next section below.
Taboola content not rendering?
- Test with the same params as the sample app, and see if those work.
- Still stuck? Submit a question on our forum.
What's next?
- For handling clicks and other important events, see Event Handling.
- In order to provide personalized recommendations for impressions in the EU and California, make sure to implement GDPR and CCPA respectively.
- If you have not already done so, make sure to look at our sample app.
- Once you are complete, submit your app for review - see the App Verification section.
IMPORTANT
Prior to launch, you must provide Taboola with a test app for verification. Skipping this step may result in a significant loss of revenue.
See: App Verification
Updated 4 days ago