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){//CallAndroidinterfacewindow.AnalyticsWebInterface.logEvent(name,JSON.stringify(params));}elseif(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.firebase){//CalliOSinterfacevarmessage={command:'logEvent',name:name,parameters:params};window.webkit.messageHandlers.firebase.postMessage(message);}else{//NoAndroidoriOSinterfacefoundconsole.log("No native APIs found.");}}functionsetUserProperty(name,value){if(!name||!value){return;}if(window.AnalyticsWebInterface){//CallAndroidinterfacewindow.AnalyticsWebInterface.setUserProperty(name,value);}elseif(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.firebase){//CalliOSinterfacevarmessage={command:'setUserProperty',name:name,value:value};window.webkit.messageHandlers.firebase.postMessage(message);}else{//NoAndroidoriOSinterfacefoundconsole.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"withparameterslogEvent("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*)userContentControllerdidReceiveScriptMessage:(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:selfname:@"firebase"];

Next Steps

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