Use Analytics in a WebView


Calls to log events or set user properties fired from within a WebView must be forwarded to native code before they can be sent to Google Analytics.

Implement JavaScript handler

The first step in using Google Analytics in a WebView is to create JavaScript functions to forward events and user properties to native code. The following example shows how to do this in a way that is compatible with both Android and Apple native code:
functionlogEvent(name,params){
if(!name){
return;
}
if(window.AnalyticsWebInterface){
//CallAndroidinterface
window.AnalyticsWebInterface.logEvent(name,JSON.stringify(params));
}elseif(window.webkit
 && window.webkit.messageHandlers
 && window.webkit.messageHandlers.firebase){
//CalliOSinterface
varmessage={
command:'logEvent',
name:name,
parameters:params
};
window.webkit.messageHandlers.firebase.postMessage(message);
}else{
//NoAndroidoriOSinterfacefound
console.log("No native APIs found.");
}
}
functionsetUserProperty(name,value){
if(!name||!value){
return;
}
if(window.AnalyticsWebInterface){
//CallAndroidinterface
window.AnalyticsWebInterface.setUserProperty(name,value);
}elseif(window.webkit
 && window.webkit.messageHandlers
 && window.webkit.messageHandlers.firebase){
//CalliOSinterface
varmessage={
command:'setUserProperty',
name:name,
value:value
};
window.webkit.messageHandlers.firebase.postMessage(message);
}else{
//NoAndroidoriOSinterfacefound
console.log("No native APIs found.");
}
}

Call the JavaScript handler from your WebView

You can properly log events and set user properties from within a WebView by calling the JavaScript functions that you defined in the previous step. The following example shows how to properly log a purchase event and set a user property as an example:
functionlogEventExample(){

//Loganeventnamed"purchase"withparameters
logEvent("purchase",{
content_type:"product",
value:123,
currency:"USD",
quantity:2,
items:[{
item_id:"sample-item-id",
item_variant:"232323"
}],
transaction_id:"1234567"
});
}
functionlogUserPropertyExample(){
//Setauserpropertynamed'favorite_genre'
setUserProperty("favorite_genre","comedy")
}

Implement native interface

To invoke native Apple code from JavaScript, create a message handler class conforming to the WKScriptMessageHandler protocol. You can make Google Analytics calls inside the userContentController:didReceiveScriptMessage: callback:

Swift

Note: This Firebase product is not available on the macOS target.
funcuserContentController(_userContentController:WKUserContentController,
didReceivemessage:WKScriptMessage){
guardletbody=message.bodyas?[String:Any]else{return}
guardletcommand=body["command"]as?Stringelse{return}
guardletname=body["name"]as?Stringelse{return}
ifcommand=="setUserProperty"{
guardletvalue=body["value"]as?Stringelse{return}
Analytics.setUserProperty(value,forName:name)
}elseifcommand=="logEvent"{
guardletparams=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"]){
[FIRAnalyticssetUserPropertyString:message.body[@"value"]forName:message.body[@"name"]];
}elseif([message.body[@"command"]isEqual:@"logEvent"]){
[FIRAnalyticslogEventWithName:message.body[@"name"]parameters:message.body[@"parameters"]];
}
}

Finally, add the message handler to the webview's user content controller:

Swift

Note: This Firebase product is not available on the macOS target.
self.webView.configuration.userContentController.add(self,name:"firebase")

Objective-C

Note: This Firebase product is not available on the macOS target.
[self.webView.configuration.userContentControlleraddScriptMessageHandler:self
name:@"firebase"];

Log in-app purchase events manually in a WebView on iOS

You can manually log IAP events in a WebView using Analytics SDK v12.5.0 or higher.

functionlogManualPurchaseEvent(){
// 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,
});
}

Note that the SDK will continue to automatically log in-app purchases where possible, and won't de-duplicate any manually logged in-app purchase events.

Next Steps

For a fully functional implementation of Google Analytics in a WebView, see the analytics-webview sample.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年11月06日 UTC.