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."); } }
Chiamare 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
Per richiamare il codice Apple nativo da JavaScript, crea una classe di gestore dei messaggi
conforme al protocollo WKScriptMessageHandler. Puoi effettuare chiamate
Google Analytics all'interno del
callback userContentController:didReceiveScriptMessage::
Swift
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
self.webView.configuration.userContentController.add(self, name: "firebase")
Objective-C
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"firebase"];
Registrare manualmente gli eventi in_app_purchase 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.