Utilizzare Analytics in una WebView

Le chiamate per registrare eventi o impostare proprietà utente attivate da una WebView devono essere inoltrate al codice nativo prima di poter essere inviate a Google Analytics.

Implementare il gestore JavaScript

Il primo passaggio per utilizzare Google Analytics in una WebView consiste nel creare funzioni JavaScript per inoltrare eventi e proprietà utente al codice nativo. L'esempio seguente mostra come eseguire questa operazione in modo compatibile con il codice nativo di Android e Apple:
function logEvent(name, params) {
  if (!name) {
    return;
  }

  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.logEvent(name, JSON.stringify(params));
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'logEvent',
      name: name,
      parameters: params
    };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}

function setUserProperty(name, value) {
  if (!name || !value) {
    return;
  }

  if (window.AnalyticsWebInterface) {
    // Call Android interface
    window.AnalyticsWebInterface.setUserProperty(name, value);
  } else if (window.webkit
      && window.webkit.messageHandlers
      && window.webkit.messageHandlers.firebase) {
    // Call iOS interface
    var message = {
      command: 'setUserProperty',
      name: name,
      value: value
   };
    window.webkit.messageHandlers.firebase.postMessage(message);
  } else {
    // No Android or iOS interface found
    console.log("No native APIs found.");
  }
}

Chiama il gestore JavaScript da WebView

Puoi registrare correttamente gli eventi e impostare le proprietà utente all'interno di una WebView chiamando le funzioni JavaScript che hai definito nel passaggio precedente. L'esempio seguente mostra come registrare correttamente un evento di acquisto e impostare una proprietà utente come esempio:
function logEventExample() {
   
   // Log an event named "purchase" with parameters
   logEvent("purchase", {
      content_type: "product",
      value: 123,
      currency: "USD",
      quantity: 2,
      items: [{
        item_id: "sample-item-id",
        item_variant: "232323"
      }],
      transaction_id: "1234567"
   });
}

function logUserPropertyExample() {
   // Set a user property named 'favorite_genre'
   setUserProperty("favorite_genre", "comedy")    
}

Implementare l'interfaccia nativa

Puoi implementare un'interfaccia nativa per iOS o Android.

iOS

Per richiamare il codice Apple nativo da JavaScript, crea una classe di gestione dei messaggi conforme al protocollo WKScriptMessageHandler. Puoi effettuare chiamate Google Analytics all'interno del callback userContentController:didReceiveScriptMessage::

Swift

Nota:questo prodotto Firebase non è disponibile sulla piattaforma di destinazione macOS.
func userContentController(_ userContentController: WKUserContentController,
                         didReceive message: WKScriptMessage) {
  guard let body = message.body as? [String: Any] else { return }
  guard let command = body["command"] as? String else { return }
  guard let name = body["name"] as? String else { return }

  if command == "setUserProperty" {
    guard let value = body["value"] as? String else { return }
    Analytics.setUserProperty(value, forName: name)
  } else if command == "logEvent" {
    guard let params = body["parameters"] as? [String: NSObject] else { return }
    Analytics.logEvent(name, parameters: params)
  }
}

Objective-C

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
  if ([message.body[@"command"] isEqual:@"setUserProperty"]) {
    [FIRAnalytics setUserPropertyString:message.body[@"value"] forName:message.body[@"name"]];
  } else if ([message.body[@"command"] isEqual: @"logEvent"]) {
    [FIRAnalytics logEventWithName:message.body[@"name"] parameters:message.body[@"parameters"]];
  }
}

Infine, aggiungi il gestore dei messaggi al controller dei contenuti generati dagli utenti della webview:

Swift

Nota:questo prodotto Firebase non è disponibile sulla piattaforma di destinazione macOS.
self.webView.configuration.userContentController.add(self, name: "firebase")

Objective-C

Nota:questo prodotto Firebase non è disponibile sulla piattaforma di destinazione macOS.
[self.webView.configuration.userContentController addScriptMessageHandler:self
                                                                     name:@"firebase"];

Android

Per richiamare il codice Android nativo da JavaScript, implementa una classe con metodi contrassegnati con @JavaScriptInterface:

public class AnalyticsWebInterface {

    public static final String TAG = "AnalyticsWebInterface";
    private FirebaseAnalytics mAnalytics;

    public AnalyticsWebInterface(Context context) {
        mAnalytics = FirebaseAnalytics.getInstance(context);
    }

    @JavascriptInterface
    public void logEvent(String name, String jsonParams) {
        LOGD("logEvent:" + name);
        mAnalytics.logEvent(name, bundleFromJson(jsonParams));
    }

    @JavascriptInterface
    public void setUserProperty(String name, String value) {
        LOGD("setUserProperty:" + name);
        mAnalytics.setUserProperty(name, value);
    }

    private void LOGD(String message) {
        // Only log on debug builds, for privacy
        if (BuildConfig.DEBUG) {
            Log.d(TAG, message);
        }
    }

    private Bundle bundleFromJson(String json) {
        // ...
    }

}

Una volta creata l'interfaccia nativa, registrala con WebView in modo che sia visibile al codice JavaScript in esecuzione in WebView:

// Only add the JavaScriptInterface on API version JELLY_BEAN_MR1 and above, due to
// security concerns, see link below for more information:
// https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    mWebView.addJavascriptInterface(
            new AnalyticsWebInterface(this), AnalyticsWebInterface.TAG);
} else {
    Log.w(TAG, "Not adding JavaScriptInterface, API Version: " + Build.VERSION.SDK_INT);
}

Registrare manualmente gli eventi di acquisto in-app in una WebView su iOS

Puoi registrare manualmente gli eventi IAP in una WebView utilizzando l'SDK Analytics v12.5.0 o versioni successive.

function logManualPurchaseEvent() {
  // For manually tracking in-app purchases within a WebView, log the in-app purchase event:
  logEvent("in_app_purchase", {
    currency: "USD",
    price: 0.99,
    product_id: "prod_123",
    product_name: "Product 123",
    quantity: 1,
    value: 0.99,
  });
}

Tieni presente che l'SDK continuerà a registrare automaticamente gli acquisti in-app ove possibile e non deduplicherà gli eventi in_app_purchase registrati manualmente.

Passaggi successivi

Per un'implementazione completamente funzionale di Google Analytics in una WebView, consulta l'esempio analytics-webview.