### Starting Geofence Tracking Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Initiates geofence tracking after requesting and obtaining location permissions. It sets the user's location opt-in status and starts the geofencing service. Errors during setup are logged. ```javascript async function didTouchStartTrackingGeofence() { const granted = await requestPermission('location'); if (!granted) { logInfo('Geofence: location permission denied'); return; } try { await window.insider.getCurrentUser().setLocationOptin(true); await window.insider.startTrackingGeofence(); logInfo('Geofence tracking started'); } catch (error) { logError('Error starting geofence tracking', error); } ``` -------------------------------- ### Start Geofence Tracking in Application.onCreate() Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Call Insider.Instance.startTrackingGeofence() in your Application's onCreate() method to initiate geofence tracking. This requires location permissions. ```kotlin // Application.onCreate() Insider.Instance.startTrackingGeofence() ``` -------------------------------- ### Serve HTML from Local HTTP Server Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This command starts a local HTTP server to serve HTML files from a specified directory. It's useful for rapid iteration on web content without rebuilding the app. Ensure `android:usesCleartextTraffic="true"` is set in `AndroidManifest.xml` for API 28+. ```bash python3 -m http.server 8080 --directory examplewebview/src/main/assets ``` -------------------------------- ### Request Location Permissions in Native Compose App Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Use the provided runtime permission requester helper to request location permissions before starting geofence tracking. The helper checks existing permissions and launches the request dialog if needed. ```kotlin val permissions = rememberRuntimePermissionRequester() InsiderGradientButton( text = "Start Tracking Geofence", onClick = { permissions.withLocationPermission { granted -> if (granted) Insider.Instance.startTrackingGeofence() } } ) ``` -------------------------------- ### Use Typed InsiderWebView Bridge in TypeScript Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This TypeScript example demonstrates using the strongly-typed `window.insider` bridge. All calls are type-checked at compile time. Note that event and parameter keys are typed as plain strings and must follow the SDK's naming conventions. ```typescript async function onPurchase() { const product = window.insider .createNewProduct( 'prod-123', 'Headphones', ['Audio', 'Headphones'], 'https://cdn.example.com/p/123.jpg', 199.99, 'USD' ) .setBrand('Acme') .setSalePrice(149.99) .setStock(42); await window.insider.itemPurchased('sale-789', product, { campaign: 'spring_sale' }); } ``` -------------------------------- ### Navigate to View (JavaScript) Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Changes the current view by setting a 'data-view' attribute on the body element and scrolls to the top of the page. It ensures sub-views start fresh by clearing previous state. ```javascript function navigateTo(view) { document.body.setAttribute('data-view', view); window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' }); // Sub-views always start fresh — clear any state left over from a previous visit. } ``` -------------------------------- ### Get Message Center Data - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Retrieves message center data for a specified date range and count. Logs the retrieved data or an error. ```javascript async function didTouchGetMessageCenterData() { try { const endDate = new Date(); const startDate = new Date(); startDate.setDate(startDate.getDate() - 30); const data = await window.insider.getMessageCenterData(startDate, endDate, 10); logInfo('Message center data retrieved. Count:', Array.isArray(data) ? data.length : data); } catch (error) { logError('Error getting message center data', error); } } ``` -------------------------------- ### Initialize InsiderWebView SDK in MainActivity Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This code initializes the InsiderWebView SDK by passing the WebView instance to `InsiderWebView.setupWebViewSDK`. It then loads the main demo page from the APK's assets. ```kotlin import android.app.Activity import android.os.Bundle import android.webkit.WebView import com.useinsider.insiderwebview.InsiderWebView public class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val webView = findViewById(R.id.web_view) InsiderWebView.setupWebViewSDK(webView) webView.loadUrl("file:///android_asset/index.html") } } ``` -------------------------------- ### Clone Kotlin Demo Repository Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Clone the repository and navigate into the project directory. ```bash git clone git@github.com:useinsider/KotlinDemo.git cd KotlinDemo ``` -------------------------------- ### Building Multiple Sample Products Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Generates an array of sample product objects by repeatedly calling `buildSampleProduct`. Use this to create a list of products for testing batch operations or displaying multiple items. ```javascript function buildSampleProducts(count) { const products = []; for (let i = 0; i < count; i++) products.push(buildSampleProduct(i)); return products; } ``` -------------------------------- ### Project Structure Overview Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This tree outlines the directory structure for the Kotlin Demo project, highlighting the native and webview application modules and their respective source files. ```plaintext KotlinDemo/ ├── example/ │ ├── build.gradle.kts │ └── src/main/ │ ├── AndroidManifest.xml │ ├── java/com/useinsider/kotlindemo/ │ │ ├── ExampleApplication.kt # SDK initialization & callbacks │ │ ├── MainActivity.kt │ │ ├── InsiderFirebaseMessagingService.kt │ │ ├── action/ # SDK feature implementations │ │ ├── callback/, component/, model/, navigation/, screen/, ui/, viewmodel/ │ └── res/ │ └── values/{colors,strings,themes}.xml │ ├── examplewebview/ │ ├── build.gradle.kts │ └── src/main/ │ ├── AndroidManifest.xml │ ├── java/com/useinsider/examplewebview/ │ │ ├── ExampleWebViewApplication.kt # SDK initialization & callbacks │ │ ├── MainActivity.kt │ │ └── InsiderFirebaseMessagingService.kt │ ├── assets/index.html │ └── res/ │ └── values/{colors,strings,themes}.xml │ ├── settings.gradle.kts ├── build.gradle.kts └── gradle/libs.versions.toml # Version Catalog ``` -------------------------------- ### Building a Sample Product Object Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Constructs a detailed sample product object using the Insider SDK's `createNewProduct` builder pattern. This is useful for populating product catalogs or testing product-related features. ```javascript function buildSampleProduct(suffix) { const idSuffix = suffix !== undefined ? '-' + suffix : ''; return window.insider .createNewProduct( 'productId' + idSuffix, 'productName' + idSuffix, ['tax1', 'tax2'], 'https://example.com/image.jpg', 123.45, 'USD' ) .setColor('Red') .setVoucherName('SUMMER2024') .setPromotionName('Summer Sale') .setSize('XL') .setGroupCode('GROUP-001') .setSalePrice(99.99) .setShippingCost(5.5) .setVoucherDiscount(10.0) .setPromotionDiscount(15.0) .setStock(50) .setQuantity(2) .setBrand('Insider Brand') .setGender('Unisex') .setDescription('Premium quality product with amazing features') .setSku('SKU-12345' + idSuffix) .setProductType('Electronics') .setGtin('1234567890123') .setTags( ['new', 'featured', 'bestseller']) .setInStock(true) .setProductUrl('https://example.com/products/' + 'productId' + idSuffix); } ``` -------------------------------- ### Track Sign Up Confirmation - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's sign-up confirmation event with custom parameters like method and referral source. Includes error handling. ```javascript async function didTouchSignUpConfirmation() { try { await window.insider.signUpConfirmation({ 'method': 'email', 'referral': 'campaign_123' }); logInfo('Sign up confirmation sent'); } catch (error) { logError('Error sending sign up confirmation', error); } } ``` -------------------------------- ### Module and SDK Flavor Mapping Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This table details the mapping between project modules, their flavor (Native or WebView), and the associated Insider SDKs they utilize. ```markdown | Module | Flavor | SDKs | |---|---|---| | `example` | Native | `insider` | | `examplewebview` | WebView | `insider` + `insiderwebview` | ``` -------------------------------- ### Track Visit Wishlist with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log a wishlist visit event with custom parameters, such as source and sorting preferences. Ensure `buildSampleProducts` is available. ```javascript await window.insider.visitWishlist( buildSampleProducts(5), { 'source': 'profile', 'sort_by': 'date_added' } ); logInfo('Visited wishlist (custom params)'); ``` -------------------------------- ### Configure Maven Repositories in settings.gradle.kts Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Declare the Insider Maven repository and other necessary repositories in the settings.gradle.kts file. ```kotlin dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url = uri("https://mobilesdk.useinsider.com/android") } maven { url = uri("https://developer.huawei.com/repo/") } } } ``` -------------------------------- ### Track Item Purchased with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Use this snippet to log an item purchase event with custom parameters. Ensure the `buildSampleProduct` function is defined and accessible. ```javascript await window.insider.itemPurchased( 'orderId-12345', buildSampleProduct(), { 'payment_method': 'credit_card', 'installments': 3 } ); logInfo('Item purchased (custom params)'); ``` -------------------------------- ### Track Visit Product Details Page - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to a product details page using a sample product object. Includes error handling. ```javascript async function didTouchVisitProductPage() { try { await window.insider.visitProductDetailsPage(buildSampleProduct()); logInfo('Visited product details page'); } catch (error) { logError('Error visiting product page', error); } } ``` -------------------------------- ### Define SDK Versions in libs.versions.toml Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Pin SDK versions in the gradle/libs.versions.toml file. Use '+' for the latest version or specify a version number. ```toml [versions] insider_sdk = "+ # e.g.: 16.0.3" insider_webview = "+ # e.g.: 1.0.0" [libraries] insider_sdk = { module = "com.useinsider:insider", version.ref = "insider_sdk" } insider_webview = { module = "com.useinsider:insiderwebview", version.ref = "insider_webview" } ``` -------------------------------- ### Initialize Insider SDK in Application Class Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Initialize the Insider SDK in your Application subclass's onCreate method. Optionally, register callbacks for SDK events like notification opens or in-app impressions. ```kotlin import android.app.Application import com.useinsider.insider.Insider import com.useinsider.insider.InsiderCallbackType public class ExampleApplication : Application() { override fun onCreate() { super.onCreate() Insider.Instance.init(this, BuildConfig.PARTNER_NAME) // Optional: register a callback for SDK events Insider.Instance.registerInsiderCallback { data, callbackType -> when (callbackType) { InsiderCallbackType.NOTIFICATION_OPEN -> { /* push tapped */ } InsiderCallbackType.INAPP_SEEN -> { /* in-app impression */ } InsiderCallbackType.INAPP_BUTTON_CLICK -> { /* in-app button */ } InsiderCallbackType.TEMP_STORE_CUSTOM_ACTION-> { /* custom action */ } InsiderCallbackType.TEMP_STORE_PURCHASE -> { /* purchase */ } InsiderCallbackType.TEMP_STORE_ADDED_TO_CART-> { /* add to cart */ } InsiderCallbackType.SESSION_STARTED -> { /* session start */ } } } } } ``` -------------------------------- ### Track Visit Wishlist Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log an event when a user visits the wishlist. Requires a function `buildSampleProducts` to generate sample product data. ```javascript await window.insider.visitWishlist(buildSampleProducts(5)); logInfo('Visited wishlist'); ``` -------------------------------- ### Track Item Added to Wishlist with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log an item added to wishlist event with custom parameters, like source and notification preferences. Ensure `buildSampleProduct` is defined. ```javascript await window.insider.itemAddedToWishlist( buildSampleProduct(), { 'source': 'product_detail', 'notify_price_drop': true } ); logInfo('Item added to wishlist (custom params)'); ``` -------------------------------- ### Track Item Purchased - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an item purchased event with an order ID and sample product details. Includes error handling. ```javascript async function didTouchItemPurchased() { try { await window.insider.itemPurchased('orderId-12345', buildSampleProduct()); logInfo('Item purchased'); } catch (error) { logError('Error purchasing item', error); } } ``` -------------------------------- ### Track Visit Product Details Page with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to a product details page with custom parameters like source and position. Handles potential errors. ```javascript async function didTouchVisitProductPageCustom() { try { await window.insider.visitProductDetailsPage( buildSampleProduct(), { 'source': 'recommendation', 'position': 3 } ); logInfo('Visited product details page (custom params)'); } catch (error) { logError('Error visiting product page', error); } } ``` -------------------------------- ### Configure Partner Name in build.gradle.kts Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Set the partner name in the build.gradle.kts file. This value is used by the SDK at runtime and exposed as BuildConfig.PARTNER_NAME. ```kotlin val partnerName = "YOUR_PARTNER_NAME" ``` -------------------------------- ### Set WhatsApp Opt-in Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Configures the user's WhatsApp opt-in status. Use a boolean value. ```javascript async function didTouchSetWhatsAppOptin(optin) { try { await window.insider.getCurrentUser().setWhatsappOptin(optin); logInfo('WhatsApp opt-in set to', optin); } catch (error) { logError('Error setting WhatsApp opt-in', error); } } ``` -------------------------------- ### Set JAVA_HOME for JDK 21 Source: https://github.com/useinsider/kotlindemo/blob/main/README.md If using AGP 9 and your JAVA_HOME is older, point Gradle to Android Studio's bundled JBR by setting the JAVA_HOME environment variable. ```bash export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" ``` -------------------------------- ### Track Visit Cart Page - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to the cart page with a specified number of sample products. Includes error handling. ```javascript async function didTouchVisitCartPage() { try { await window.insider.visitCartPage(buildSampleProducts(5)); logInfo('Visited cart page'); } catch (error) { logError('Error visiting cart page', error); } } ``` -------------------------------- ### Set Push Opt-in Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Configures the user's push notification opt-in status. Use a boolean value. ```javascript async function didTouchSetPushOptin(optin) { try { await window.insider.getCurrentUser().setPushOptin(optin); logInfo('Push opt-in set to', optin); } catch (error) { logError('Error setting push opt-in', error); } } ``` -------------------------------- ### Consume SDK Dependencies in build.gradle.kts Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Include the Insider SDK dependencies in your module's build.gradle.kts file. Use the -nh variant if not targeting Huawei devices. ```kotlin dependencies { // Native SDK (required by both modules) implementation(libs.insider.sdk) // WebView SDK (only in :examplewebview) // implementation(libs.insider.webview) // Use the -nh variant of insider if you do not target Huawei devices // implementation("com.useinsider:insider:16.0.3-nh") } ``` -------------------------------- ### Track Item Purchased with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an item purchased event with custom parameters. Handles potential errors. ```javascript async function didTouchItemPurchasedCustom() { try { // Code for custom parameters not fully provided in source ``` -------------------------------- ### Track Visit Home Page with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to the home page with custom parameters, such as interaction methods and counts. Handles potential errors. ```javascript async function didTouchVisitHomePageCustom() { try { await window.insider.visitHomePage({ 'method': ['tabBar', 'toolBar'], 'count': [4.9, 5.5, 6], 'date': new Date(), }); logInfo('Visited home page (custom params)'); } catch (error) { logError('Error visiting home page', error); } } ``` -------------------------------- ### Track Visit Listing Page - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to a listing page with specified categories. Includes error handling. ```javascript async function didTouchVisitListingPage() { try { await window.insider.visitListingPage(['Erkek', 'T-shirt', 'Adidas']); logInfo('Visited listing page'); } catch (error) { logError('Error visiting listing page', error); } } ``` -------------------------------- ### Track Item Added to Wishlist Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log an event when an item is added to the wishlist. Requires a `buildSampleProduct` function. ```javascript await window.insider.itemAddedToWishlist(buildSampleProduct()); logInfo('Item added to wishlist'); ``` -------------------------------- ### Visit Wishlist Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an event when a user visits their wishlist. Accepts custom parameters for tracking the source and sorting preferences. ```APIDOC ## visitWishlist ### Description Logs an event when a user visits their wishlist. This method can accept a list of products and custom parameters to provide context about the visit. ### Method `await window.insider.visitWishlist(products, customParameters)` ### Parameters - **products** (array) - Required - A list of products in the wishlist. - **customParameters** (object) - Optional - An object containing additional information, such as the source of the visit or sorting preferences. ### Request Example ```javascript await window.insider.visitWishlist( buildSampleProducts(5), { 'source': 'profile', 'sort_by': 'date_added' } ); ``` ``` -------------------------------- ### Track Visit Home Page - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to the home page. Includes basic error handling. ```javascript async function didTouchVisitHomePage() { try { await window.insider.visitHomePage(); logInfo('Visited home page'); } catch (error) { logError('Error visiting home page', error); } } ``` -------------------------------- ### Track Visit Listing Page with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to a listing page with custom sorting and filtering parameters. Handles potential errors. ```javascript async function didTouchVisitListingPageCustom() { try { await window.insider.visitListingPage( ['Erkek', 'T-shirt', 'Adidas'], { 'sort_by': 'price', 'filter_brand': 'Adidas' } ); logInfo('Visited listing page (custom params)'); } catch (error) { logError('Error visiting listing page', error); } } ``` -------------------------------- ### Load HTML from Local HTTP Server Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Load an HTML page served from a local HTTP server. This is typically used during development for faster refresh cycles. Note that Android may block plaintext HTTP traffic; configure `AndroidManifest.xml` or Network Security Config accordingly. ```kotlin webView.loadUrl("http://localhost:8080/index.html") // emulator → host ``` -------------------------------- ### Product Actions Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Methods for tracking user interactions with products, such as adding to or removing from the cart, and purchasing. ```APIDOC ## itemAddedToCart ### Description Tracks an item being added to the cart. ### Method `await window.insider.itemAddedToCart(product)` ### Parameters #### Request Body - **product** (Object) - Required - The product object that was added to the cart. ## itemAddedToCartCustom ### Description Tracks an item being added to the cart with custom parameters. ### Method `await window.insider.itemAddedToCart(product, customParameters)` ### Parameters #### Request Body - **product** (Object) - Required - The product object that was added to the cart. - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## itemRemovedFromCart ### Description Tracks an item being removed from the cart. ### Method `await window.insider.itemRemovedFromCart(productId)` ### Parameters #### Path Parameters - **productId** (String) - Required - The ID of the product removed from the cart. ## itemRemovedFromCartCustom ### Description Tracks an item being removed from the cart with custom parameters. ### Method `await window.insider.itemRemovedFromCart(productId, customParameters)` ### Parameters #### Path Parameters - **productId** (String) - Required - The ID of the product removed from the cart. #### Request Body - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## itemPurchased ### Description Tracks an item being purchased. ### Method `await window.insider.itemPurchased(orderId, product)` ### Parameters #### Path Parameters - **orderId** (String) - Required - The ID of the order. #### Request Body - **product** (Object) - Required - The product object that was purchased. ## itemPurchasedCustom ### Description Tracks an item being purchased with custom parameters. ### Method `await window.insider.itemPurchased(orderId, product, customParameters)` ### Parameters #### Path Parameters - **orderId** (String) - Required - The ID of the order. #### Request Body - **product** (Object) - Required - The product object that was purchased. - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ``` -------------------------------- ### Apply Google Services Plugin Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Apply the Google Services plugin in your module's build.gradle file to enable Firebase integration. ```kotlin plugins { alias(libs.plugins.google.services) } ``` -------------------------------- ### Opt-in and Collection Settings Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Functions to manage user consent for data collection and communication channels. ```APIDOC ## enableIpCollection ### Description Enables or disables the collection of IP addresses for the user. ### Method `async function didTouchEnableIpCollection(enable)` ### Parameters - **enable** (boolean) - `true` to enable IP collection, `false` to disable. ### Request Example ```javascript // Enable IP collection didTouchEnableIpCollection(true); // Disable IP collection didTouchEnableIpCollection(false); ``` ### Response Logs the status of IP collection setting. ### Error Handling Logs errors if setting IP collection fails. ``` ```APIDOC ## enableCarrierCollection ### Description Enables or disables the collection of carrier information for the user. ### Method `async function didTouchEnableCarrierCollection(enable)` ### Parameters - **enable** (boolean) - `true` to enable carrier collection, `false` to disable. ### Request Example ```javascript // Enable carrier collection didTouchEnableCarrierCollection(true); // Disable carrier collection didTouchEnableCarrierCollection(false); ``` ### Response Logs the status of carrier collection setting. ### Error Handling Logs errors if setting carrier collection fails. ``` ```APIDOC ## enableLocationCollection ### Description Enables or disables the collection of location data for the user. ### Method `async function didTouchEnableLocationCollection(enable)` ### Parameters - **enable** (boolean) - `true` to enable location collection, `false` to disable. ### Request Example ```javascript // Enable location collection didTouchEnableLocationCollection(true); // Disable location collection didTouchEnableLocationCollection(false); ``` ### Response Logs the status of location collection setting. ### Error Handling Logs errors if setting location collection fails. ``` ```APIDOC ## setEmailOptin ### Description Sets the user's opt-in preference for receiving emails. ### Method `async function didTouchSetEmailOptin(optin)` ### Parameters - **optin** (boolean) - `true` to opt-in for emails, `false` to opt-out. ### Request Example ```javascript // Opt-in for emails didTouchSetEmailOptin(true); // Opt-out of emails didTouchSetEmailOptin(false); ``` ### Response Logs the email opt-in status. ### Error Handling Logs errors if setting email opt-in fails. ``` ```APIDOC ## setPushOptin ### Description Sets the user's opt-in preference for receiving push notifications. ### Method `async function didTouchSetPushOptin(optin)` ### Parameters - **optin** (boolean) - `true` to opt-in for push notifications, `false` to opt-out. ### Request Example ```javascript // Opt-in for push notifications didTouchSetPushOptin(true); // Opt-out of push notifications didTouchSetPushOptin(false); ``` ### Response Logs the push opt-in status. ### Error Handling Logs errors if setting push opt-in fails. ``` ```APIDOC ## setLocationOptin ### Description Sets the user's opt-in preference for receiving location-based notifications or services. ### Method `async function didTouchSetLocationOptin(optin)` ### Parameters - **optin** (boolean) - `true` to opt-in for location services, `false` to opt-out. ### Request Example ```javascript // Opt-in for location services didTouchSetLocationOptin(true); // Opt-out of location services didTouchSetLocationOptin(false); ``` ### Response Logs the location opt-in status. ### Error Handling Logs errors if setting location opt-in fails. ``` ```APIDOC ## setSMSOptin ### Description Sets the user's opt-in preference for receiving SMS messages. ### Method `async function didTouchSetSMSOptin(optin)` ### Parameters - **optin** (boolean) - `true` to opt-in for SMS, `false` to opt-out. ### Request Example ```javascript // Opt-in for SMS didTouchSetSMSOptin(true); // Opt-out of SMS didTouchSetSMSOptin(false); ``` ### Response Logs the SMS opt-in status. ### Error Handling Logs errors if setting SMS opt-in fails. ``` ```APIDOC ## setWhatsAppOptin ### Description Sets the user's opt-in preference for receiving WhatsApp messages. ### Method `async function didTouchSetWhatsAppOptin(optin)` ### Parameters - **optin** (boolean) - `true` to opt-in for WhatsApp, `false` to opt-out. ### Request Example ```javascript // Opt-in for WhatsApp didTouchSetWhatsAppOptin(true); // Opt-out of WhatsApp didTouchSetWhatsAppOptin(false); ``` ### Response Logs the WhatsApp opt-in status. ### Error Handling Logs errors if setting WhatsApp opt-in fails. ``` -------------------------------- ### Track Wishlist Cleared with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log a wishlist cleared event with custom parameters, including the reason and item count. Useful for detailed analytics. ```javascript await window.insider.wishlistCleared({ 'reason': 'bulk_add_to_cart', 'item_count': 3 }); logInfo('Wishlist cleared (custom params)'); ``` -------------------------------- ### Configure Application ID in build.gradle.kts Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Set the application ID in the build.gradle.kts file. This must match the package registered in your google-services.json. ```kotlin applicationId = "com.your.package.name" ``` -------------------------------- ### User Login Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user into the Insider SDK, creating identifiers with email, phone, user ID, and custom attributes. Returns the Insider ID upon successful login. ```javascript async function didTouchLogin() { try { const identifiers = window.insider.createIdentifiers() .addEmail(generateRandomString(10) + '@example.com') .addPhoneNumber('+' + generateRandomNumber(12)) .addUserID(generateRandomString(8)) .addCustomIdentifier('loyalty\_level', 'gold') .addCustomIdentifier('preferred\_language', 'en'); const insiderID = await window.insider.getCurrentUser().login(identifiers); logInfo('Logged in. Insider ID:', insiderID); } catch (error) { logError('Error logging in', error); } } ``` -------------------------------- ### Track Item Added to Cart - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an event when an item is added to the cart, using a sample product object. Includes error handling. ```javascript async function didTouchItemAddedToCart() { try { await window.insider.itemAddedToCart(buildSampleProduct()); logInfo('Item added to cart'); } catch (error) { logError('Error adding item to cart', error); } } ``` -------------------------------- ### Request Runtime Permission (JavaScript) Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Requests a runtime permission from the native layer. It returns a Promise that resolves with a boolean indicating whether the permission was granted. If the bridge is not available, it defaults to granting the permission. ```javascript var pendingPermissionResolvers = {}; window._permissionResolve = function (callbackId, granted) { const resolve = pendingPermissionResolvers[callbackId]; if (!resolve) return; delete pendingPermissionResolvers[callbackId]; resolve(!!granted); }; function requestPermission(kind) { return new Promise(function (resolve) { const bridge = window.Permissions; if (!bridge || typeof bridge.request !== 'function') { resolve(true); return; } const callbackId = 'permission-' + Math.random().toString(36).slice(2, 8); pendingPermissionResolvers[callbackId] = resolve; bridge.request(kind, callbackId); }); } ``` -------------------------------- ### Enabling IDFA Collection (iOS) Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html A placeholder function intended to enable IDFA collection. Note that this functionality is iOS-specific and not applicable to web environments. ```javascript function didTouchEnableIDFACollection(enable) { // iOS-only — no IDFA on web. ``` -------------------------------- ### Load HTML from APK Assets Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Use this method to load an HTML file that is packaged within the application's APK. The `file:///android_asset/` scheme is used to access these assets. ```kotlin webView.loadUrl("file:///android_asset/index.html") ``` -------------------------------- ### Set Email Opt-in Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Updates the user's email opt-in status. Pass a boolean to indicate their preference. ```javascript async function didTouchSetEmailOptin(optin) { try { await window.insider.getCurrentUser().setEmailOptin(optin); logInfo('Email opt-in set to', optin); } catch (error) { logError('Error setting email opt-in', error); } } ``` -------------------------------- ### Reference InsiderWebView TypeScript Definitions Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Alternatively, use a triple-slash reference in your entry TypeScript file to include the bridge's type definitions. This makes `window.insider` strongly typed without needing an import statement. ```typescript /// ``` -------------------------------- ### Set Location Opt-in Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Manages the user's opt-in status for location-based services. Accepts a boolean. ```javascript async function didTouchSetLocationOptin(optin) { try { await window.insider.getCurrentUser().setLocationOptin(optin); logInfo('Location opt-in set to', optin); } catch (error) { logError('Error setting location opt-in', error); } } ``` -------------------------------- ### Event Tracking Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Methods for tracking various user actions and page views. ```APIDOC ## visitHomePage ### Description Tracks a user visiting the home page. ### Method `await window.insider.visitHomePage()` ## visitHomePageCustom ### Description Tracks a user visiting the home page with custom parameters. ### Method `await window.insider.visitHomePage(customParameters)` ### Parameters #### Request Body - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## visitListingPage ### Description Tracks a user visiting a listing page. ### Method `await window.insider.visitListingPage(categories)` ### Parameters #### Path Parameters - **categories** (Array of Strings) - Required - An array of category names. ## visitListingPageCustom ### Description Tracks a user visiting a listing page with custom parameters. ### Method `await window.insider.visitListingPage(categories, customParameters)` ### Parameters #### Path Parameters - **categories** (Array of Strings) - Required - An array of category names. #### Request Body - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## visitProductDetailsPage ### Description Tracks a user visiting a product details page. ### Method `await window.insider.visitProductDetailsPage(product)` ### Parameters #### Request Body - **product** (Object) - Required - Product object containing details. ## visitProductDetailsPageCustom ### Description Tracks a user visiting a product details page with custom parameters. ### Method `await window.insider.visitProductDetailsPage(product, customParameters)` ### Parameters #### Request Body - **product** (Object) - Required - Product object containing details. - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## visitCartPage ### Description Tracks a user visiting the cart page. ### Method `await window.insider.visitCartPage(products)` ### Parameters #### Request Body - **products** (Array of Objects) - Required - An array of product objects in the cart. ## visitCartPageCustom ### Description Tracks a user visiting the cart page with custom parameters. ### Method `await window.insider.visitCartPage(products, customParameters)` ### Parameters #### Request Body - **products** (Array of Objects) - Required - An array of product objects in the cart. - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ## signUpConfirmation ### Description Tracks that a sign-up confirmation has been sent. ### Method `await window.insider.signUpConfirmation(customParameters)` ### Parameters #### Request Body - **customParameters** (Object) - Optional - Custom key-value pairs to associate with the event. ``` -------------------------------- ### Executing a Custom Action Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Placeholder function to execute custom actions within the webview. It logs an informational message suggesting where to implement custom logic, such as tagging an event. ```javascript function didTouchCustomAction() { logInfo('Run your custom action here (demo/index.html). e.g., window.insider.tagEvent("ping").build()'); } ``` -------------------------------- ### Track Visit Cart Page with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a user's visit to the cart page with custom parameters, such as coupon application status and cart source. Handles potential errors. ```javascript async function didTouchVisitCartPageCustom() { try { await window.insider.visitCartPage( buildSampleProducts(5), { 'coupon_applied': true, 'cart_source': 'wishlist' } ); logInfo('Visited cart page (custom params)'); } catch (error) { logError('Error visiting cart page', error); } } ``` -------------------------------- ### Item Purchased Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an item purchase event. This method can accept custom parameters for detailed tracking. ```APIDOC ## itemPurchased ### Description Logs an item purchase event with an order ID, product details, and optional custom payment parameters. ### Method `await window.insider.itemPurchased(orderId, productDetails, customParameters)` ### Parameters - **orderId** (string) - Required - The unique identifier for the order. - **productDetails** (object) - Required - An object containing details about the purchased product(s). - **customParameters** (object) - Optional - An object containing additional payment or transaction details. ### Request Example ```javascript await window.insider.itemPurchased( 'orderId-12345', buildSampleProduct(), { 'payment_method': 'credit_card', 'installments': 3 } ); ``` ``` -------------------------------- ### Send Custom Event with Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Sends a custom event to Insider with specified parameters. It reads event name and parameters from the DOM, coerces parameter values, and logs success or failure details. Ensure 'event-name' input and parameter rows are present. ```javascript async function sendCustomEvent() { try { const eventName = document.getElementById('event-name').value.trim(); if (!eventName) { logError('Custom Event', new Error('Event name is required')); return; } const event = window.insider.tagEvent(eventName); const rows = readParamRows('event-params'); const added = []; const skipped = []; for (const { type, name, rawValue } of rows) { if (!name) { skipped.push(''); continue; } const coerced = coerceParamValue(type, rawValue); if (!coerced.ok) { skipped.push(name + ' [' + coerced.reason + ']'); continue; } try { switch (type) { case 'String': event.addStringParameter(name, coerced.value); break; case 'Integer': case 'Double': event.addNumericParameter(name, coerced.value); break; case 'Boolean': event.addBooleanParameter(name, coerced.value); break; } added.push(name + '=' + JSON.stringify(coerced.value)); } catch (e) { skipped.push(name + ' [' + (e && e.message ? e.message : String(e)) + ']'); } } await event.build(); const addedMsg = added.length ? ' params(' + added.length + '): ' + added.join(', ') : ' (no params)'; const skipMsg = skipped.length ? ' | skipped: ' + skipped.join(', ') : ''; logInfo('Event sent "' + eventName + '"' + addedMsg + skipMsg); navigateTo('main'); } catch (error) { logError('Error sending custom event', error); } } ``` -------------------------------- ### Configure TypeScript for InsiderWebView Bridge Source: https://github.com/useinsider/kotlindemo/blob/main/README.md This `tsconfig.json` configuration includes the TypeScript definition file for the InsiderWebView bridge. This enables type-safety and autocompletion for the JavaScript bridge in your web application. ```json { "include": ["src/**/*", "src/types/InsiderWebViewScript.d.ts"] } ``` -------------------------------- ### Log Unsupported Feature (JavaScript) Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs a warning or info message indicating that a specific feature is not supported in the WebView SDK and updates the 'printLabel' element. ```javascript function logUnsupported(name) { const message = name + ' is not supported in the WebView SDK'; setPrintLabel(message); window._insiderLogger.warn ? window._insiderLogger.warn(message) : window._insiderLogger.info(message); } ``` -------------------------------- ### User Logout Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs the current user out of the Insider SDK. This action is irreversible for the current session. ```javascript async function didTouchLogout() { try { await window.insider.getCurrentUser().logout(); logInfo('User logged out'); } catch (error) { logError('Error logging out', error); } } ``` -------------------------------- ### Add Location Dependency to build.gradle.kts Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Include the play services location library in your project's build.gradle.kts file to enable geofence tracking. ```kotlin // build.gradle.kts implementation(libs.play.services.location) ``` -------------------------------- ### Inject PermissionBridge into WebView Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Register a PermissionBridge instance with your WebView to allow JavaScript to trigger native permission dialogs. This is used in the examplewebview module. ```kotlin webView.addJavascriptInterface( PermissionBridge(activity = this, webView = webView, requestPush = ..., requestLocation = ...), "Permissions" ) ``` -------------------------------- ### Add Huawei Messaging Dependencies Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Include the necessary Huawei Mobile Services dependencies for push, ads, and location services if targeting Huawei devices. ```kotlin implementation(libs.huawei.push) implementation(libs.huawei.ads) implementation(libs.huawei.location) ``` -------------------------------- ### Track Wishlist Cleared Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log an event when the entire wishlist is cleared. This is a simple event without parameters. ```javascript await window.insider.wishlistCleared(); logInfo('Wishlist cleared'); ``` -------------------------------- ### Enable IP Collection Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Controls the collection of IP addresses. Pass a boolean value to enable or disable. ```javascript async function didTouchEnableIpCollection(enable) { try { await window.insider.enableIpCollection(enable); logInfo('IP collection set to', enable); } catch (error) { logError('Error setting IP collection', error); } } ``` -------------------------------- ### Track Item Removed from Wishlist with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log an item removed from wishlist event with custom parameters, such as the reason for removal. Requires the product ID. ```javascript await window.insider.itemRemovedFromWishlist('productId', { 'reason': 'purchased' }); logInfo('Item removed from wishlist (custom params)'); ``` -------------------------------- ### Set SMS Opt-in Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Updates the user's SMS notification opt-in status. Pass a boolean to confirm. ```javascript async function didTouchSetSMSOptin(optin) { try { await window.insider.getCurrentUser().setSMSOptin(optin); logInfo('SMS opt-in set to', optin); } catch (error) { logError('Error setting SMS opt-in', error); } } ``` -------------------------------- ### Register Application Class in AndroidManifest.xml Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Declare your custom Application class in the AndroidManifest.xml file to ensure it's used by the application. ```xml ``` -------------------------------- ### Item Added to Wishlist Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an event when an item is added to the wishlist. Custom parameters can be included for source and notification preferences. ```APIDOC ## itemAddedToWishlist ### Description Logs an event when an item is added to the user's wishlist. This method can accept product details and custom parameters for tracking purposes. ### Method `await window.insider.itemAddedToWishlist(productDetails, customParameters)` ### Parameters - **productDetails** (object) - Required - An object containing details about the added product. - **customParameters** (object) - Optional - An object containing additional information, such as the source of the addition or notification preferences. ### Request Example ```javascript await window.insider.itemAddedToWishlist( buildSampleProduct(), { 'source': 'product_detail', 'notify_price_drop': true } ); ``` ``` -------------------------------- ### Declare Permissions in AndroidManifest.xml Source: https://github.com/useinsider/kotlindemo/blob/main/README.md Add necessary permission declarations to your AndroidManifest.xml file. These are required for features like geofence tracking and push notifications. ```xml ``` -------------------------------- ### Log Info Message (JavaScript) Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an informational message to the console and updates the 'printLabel' element. If a value is provided, it's included in the log. ```javascript function logInfo(message, value) { const text = value !== undefined ? message + ' ' + String(value) : message; setPrintLabel(text); if (value !== undefined) { window._insiderLogger.info(message, value); } else { window._insiderLogger.info(message); } } ``` -------------------------------- ### Enable In-App Messages - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Call this function to enable in-app messaging for the user. Handles potential errors during the process. ```javascript async function didTouchEnableInAppMessages() { try { await window.insider.enableInAppMessages(); logInfo('Inapp messages enabled'); } catch (error) { logError('Error enabling inapp messages', error); } } ``` -------------------------------- ### Track Cart Cleared with Custom Parameters Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Log a cart cleared event with custom parameters. This is useful for tracking specific reasons why a cart might be cleared. ```javascript await window.insider.cartCleared({ 'reason': 'user_action', 'item_count': 5 }); logInfo('Cart cleared (custom params)'); ``` -------------------------------- ### Track Item Added to Cart with Custom Parameters - JavaScript Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Logs an item added to cart event with custom parameters such as source and quantity. Handles potential errors. ```javascript async function didTouchItemAddedToCartCustom() { try { await window.insider.itemAddedToCart( buildSampleProduct(), { 'source': 'product_detail', 'quantity': 2 } ); logInfo('Item added to cart (custom params)'); } catch (error) { logError('Error adding item to cart', error); } } ``` -------------------------------- ### User Attribute Management Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Functions to set various attributes for the current user. ```APIDOC ## setUserAttr ### Description Sets a specific attribute for the current user based on the `kind` provided. This function reads values from corresponding HTML input elements. ### Method `async function setUserAttr(kind)` ### Parameters - **kind** (string) - The type of user attribute to set (e.g., 'Name', 'Email', 'Birthday'). ### Supported Attributes: - Name - Surname - Email - PhoneNumber - Age - Gender - Birthday - Language - Locale ### Request Example ```javascript // To set the user's name: setUserAttr('Name'); // To set the user's birthday: setUserAttr('Birthday'); ``` ### Response Logs success or error messages based on the operation outcome. ### Error Handling Logs errors if an attribute fails to set or if required input is missing (e.g., for Birthday). ``` -------------------------------- ### Enable IDFA Collection Source: https://github.com/useinsider/kotlindemo/blob/main/examplewebview/src/main/assets/index.html Call this function to enable or disable IDFA collection. Ensure the 'enable' parameter is a boolean. ```javascript async function didTouchEnableIdfaCollection(enable) { try { await window.insider.enableIdfaCollection(enable); logInfo('IDFA collection set to', enable); } catch (error) { logError('Error setting IDFA collection', error); } } ```