Triển khai trình xử lý JavaScript
Bước đầu tiên để sử dụng Google Analytics trong WebView là tạo các hàm JavaScript để chuyển tiếp sự kiện và thuộc tính người dùng đến mã gốc. Ví dụ sau đây cho thấy cách thực hiện việc này theo cách tương thích với cả mã gốc của Android và 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."); } }
Gọi trình xử lý JavaScript từ WebView
Bạn có thể ghi nhật ký sự kiện đúng cách và đặt thuộc tính người dùng từ bên trong WebView bằng cách gọi các hàm JavaScript mà bạn đã xác định trong bước trước. Ví dụ sau đây cho thấy cách ghi nhật ký đúng cách một sự kiện mua hàng và đặt thuộc tính người dùng làm ví dụ: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") }
Triển khai giao diện gốc
Bạn có thể triển khai giao diện gốc cho iOS hoặc Android.
iOS
Để gọi mã gốc của Apple từ JavaScript, hãy tạo một lớp trình xử lý thông báo tuân thủ giao thức WKScriptMessageHandler. Bạn có thể thực hiện
Google Analytics lệnh gọi bên trong
userContentController:didReceiveScriptMessage:
lệnh gọi lại:
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"]]; } }
Cuối cùng, hãy thêm trình xử lý thông báo vào trình điều khiển nội dung người dùng của webview:
Swift
self.webView.configuration.userContentController.add(self, name: "firebase")
Objective-C
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"firebase"];
Android
Để gọi mã gốc của Android từ JavaScript, hãy triển khai một lớp có các phương thức được đánh dấu @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) { // ... } }
Sau khi tạo giao diện gốc, hãy đăng ký giao diện đó với WebView để mã JavaScript chạy trong WebView có thể nhìn thấy giao diện đó:
// 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); }
Ghi nhật ký sự kiện mua hàng trong ứng dụng theo cách thủ công trong WebView trên iOS
Bạn có thể ghi nhật ký sự kiện mua hàng trong ứng dụng (IAP) theo cách thủ công trong WebView bằng Analytics SDK phiên bản 12.5.0 trở lên.
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,
});
}
Xin lưu ý rằng SDK sẽ tiếp tục tự động ghi nhật ký các giao dịch mua hàng trong ứng dụng khi có thể và sẽ không loại bỏ các sự kiện mua hàng trong ứng dụng được ghi nhật ký theo cách thủ công.
Các bước tiếp theo
Để biết cách triển khai đầy đủ chức năng của Google Analytics trong WebView, hãy xem mẫu analytics-webview.