تنفيذ معالج JavaScript
تتمثل الخطوة الأولى لاستخدام Google Analytics في WebView في إنشاء دوال JavaScript لإعادة توجيه الأحداث وخصائص المستخدمين إلى رمز برمجي أصلي يوضح المثال التالي كيفية إجراء ذلك بطريقة متوافقة باستخدام الرمز الأصلي لكل من Android و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."); } }
تنفيذ الواجهة الأصلية
لاستدعاء رمز Android الأصلي من JavaScript، نفِّذ فئة باستخدام
تم وضع علامة @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) { // ... } }
بعد إنشاء الواجهة الأصلية، سجِّلها في WebView. كي يكون مرئيًا لرمز JavaScript الذي يتم تشغيله في 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); }
الخطوات التالية
لتنفيذ "إحصاءات Google" بشكلٍ كامل في مكوّن WebView، يُرجى الاطّلاع على الاطّلاع على محتوى الويب في "إحصاءات Google" كعينة.