Google Analytics
Integrates Google Analytics tracking with Drupal by automatically adding gtag.js JavaScript tracking code to every page.
google_analytics
インストール
composer require 'drupal/google_analytics:^4.0'
概要
Google Analyticsモジュールは、Google Analytics(GA4およびUniversal Analytics)と統合することで、DrupalウェブサイトにWeb統計トラッキング機能を追加します。必要なJavaScriptトラッキングコードをすべてのページに自動的に追加し、詳細なトラフィック分析、ユーザー行動追跡、マーケティング効果測定を可能にします。
このモジュールは、複数のGoogle Analyticsアカウント(GA4 G-プロパティ、Universal Analytics UA-、Google Ads AW-、DoubleClick DC-タグ)をサポートし、ページ、ユーザーロール、個人ユーザー設定に基づく可視性設定が可能です。外部リンク、mailto/telリンク、ファイルダウンロード、URLフラグメント、内部サイト検索、Drupalステータスメッセージなど、広範なトラッキングオプションを提供します。
高度な機能として、Token統合によるカスタムディメンションとメトリクスのサポート、クロスドメイントラッキング、パフォーマンス向上のためのローカルJavaScriptキャッシュ、プライバシー準拠のハッシュ化によるユーザーIDトラッキング、他のモジュールがトラッキング機能を拡張できるイベント駆動アーキテクチャが含まれます。
Features
- 複数のGoogle Analyticsアカウントサポート(GA4 G-、Universal Analytics UA-、Google Ads AW-、DoubleClick DC-)とドラッグ&ドロップによる順序変更
- パスパターンとワイルドカードを使用した特定ページの包含・除外によるページベースのトラッキング可視性設定
- 特定のユーザーロールをトラッキングまたは除外するロールベースのトラッキング制御
- アカウントページでのユーザーごとのオプトイン/オプトアウトトラッキング設定
- 外部ウェブサイトへの外部リンククリックトラッキング
- Mailtoおよび電話(tel:)リンククリックトラッキング
- 設定可能なファイル拡張子(50以上のデフォルト拡張子)によるファイルダウンロードトラッキング
- シングルページアプリケーション向けの個別ページビューとしてのURLフラグメントトラッキング
- Colorboxモーダルダイアログコンテンツトラッキング統合
- ページ内分析のための拡張リンクアトリビューションサポート
- 結果件数レポートを含む内部サイト検索トラッキング
- イベントとしてのDrupalステータス、警告、エラーメッセージトラッキング
- Drupal Tokenサポート付きカスタムディメンションとメトリクス
- カスタムJavaScriptコードスニペット(gtag config前後)
- 複数のトップレベルドメイン用クロスドメイントラッキング
- プライバシー準拠のIP匿名化(Universal Analytics用)
- 毎日自動更新されるローカルJavaScriptキャッシュ
- プライバシー準拠のための暗号化ハッシュによるユーザーIDトラッキング
- AdSense広告トラッキング統合
- ディスプレイ広告機能(リマーケティング、デモグラフィック、興味関心レポート)
- 翻訳セットの単一ユニットとしてのトラッキング
- 詳細なコンソールログ出力によるデバッグモード
- Drupal 6および7からの移行サポート
- 他のモジュールによる拡張のためのイベント駆動アーキテクチャ
Use Cases
Basic Website Traffic Analysis
Install the module, enter your GA4 property ID (G-xxxxxxxx), and immediately start collecting visitor data. The default configuration tracks all pages except admin paths, with IP anonymization enabled for privacy compliance. View traffic sources, user behavior, and page popularity in Google Analytics.
E-commerce Download Tracking
Enable file download tracking to monitor which documents, PDFs, software, or media files users download. The extensive default file extension list covers most common file types. Customize the extension list for your specific needs. Downloads appear as events in Google Analytics with the file extension as the event action.
Multi-site or Multi-brand Tracking
Add multiple Google Analytics property IDs to track the same site in different GA accounts. Useful for agencies managing client sites, organizations with multiple departments, or tracking in both GA4 and Universal Analytics simultaneously. Drag-and-drop to reorder accounts.
Marketing Campaign Analysis
Track outbound link clicks to see which external resources users visit. Monitor mailto: and tel: clicks to measure contact form alternatives. Enable display advertising features for remarketing campaigns and demographic/interest reporting.
User Segmentation with Custom Dimensions
Create custom dimensions in Google Analytics, then configure them in Drupal with token values like [current-user:role-names] to segment visitors by role, or use node tokens to segment by content attributes. Privacy-compliant token validation prevents accidental PII exposure.
Single-Page Application Tracking
Enable URL fragment tracking for sites using hash-based routing. Each hash change registers as a separate pageview, providing accurate page-level analytics for JavaScript-heavy applications and anchor-based navigation.
Form Usability Analysis
Enable message tracking to capture Drupal status, warning, and error messages as GA events. Identify which forms generate validation errors, which processes show warnings, and overall user experience issues through your analytics dashboard.
Cross-Domain Tracking
For organizations with multiple related domains (example.com, shop.example.com, app.example.com), configure cross-domain tracking to treat visitors as single users across all properties. Enter all domains in the cross-domains list and select 'Multiple top-level domains' mode.
GDPR/Privacy Compliant Tracking
The module installs with privacy-friendly defaults: IP anonymization enabled, authenticated users granted opt-out permission, and PII-containing tokens blocked from custom dimensions. Users can control their tracking preference on their profile page.
Performance Optimization with Local Caching
After confirming tracking works correctly, enable local JavaScript caching to serve gtag.js from your server instead of Google's CDN. The file updates automatically daily via cron, reducing external requests and improving page load times.
Tips
- Test your tracking setup using Google Analytics Real-Time reports before going live
- Use debug mode during development to see detailed tracking information in the browser console
- The default excluded paths (/admin/*, /batch, etc.) prevent tracking of admin activity that could skew analytics
- When using custom dimensions, always set up the dimension in Google Analytics first, then configure it in Drupal
- For GDPR compliance, update your privacy policy when enabling display advertising features
- Local JavaScript caching improves performance but should only be enabled after confirming tracking works
- User ID tracking uses a one-way hash - the actual Drupal user ID is never sent to Google
- Multiple GA accounts can be used to track in both GA4 and Universal Analytics during migration
- The module automatically tracks 403 and 404 error pages regardless of visibility settings for error monitoring
Technical Details
Admin Pages 1
/admin/config/services/google-analytics
Configure all Google Analytics tracking behavior including account IDs, visibility settings, link tracking, custom dimensions/metrics, and advanced JavaScript options.
権限 4
Hooks 6
hook_page_attachments
Main hook that adds the Google Analytics tracking code to every page. Checks visibility, loads accounts, dispatches events, and attaches the JavaScript.
hook_form_user_form_alter
Adds Google Analytics opt-in/opt-out checkbox to user profile forms when the user has the appropriate permission.
hook_cron
Regenerates the locally cached tracking code file daily when caching is enabled.
hook_preprocess_item_list__search_results
Collects and adds the number of search results to the page for site search tracking.
hook_entity_extra_field_info
Defines the Google Analytics settings pseudo-field on user entity forms.
hook_help
Provides help text and documentation links for the module.
Troubleshooting 10
Verify a valid Web Property ID is configured. Check page visibility settings - by default, admin pages are excluded. Ensure the current user's role is not excluded. Clear Drupal caches after configuration changes.
Navigate to /admin/config/services/google-analytics and enter a valid Google Analytics Web Property ID in the format UA-xxxxx-yy or G-xxxxxxxx.
Debug mode loads a larger JavaScript file and should only be used during development. Disable it at /admin/config/services/google-analytics under Advanced settings before going to production.
Custom dimensions must first be created in the Google Analytics Management Interface before they can be used in Drupal. Ensure the index numbers match between GA and your Drupal configuration.
Verify the file extension is included in the file extensions list. Extensions are case-insensitive and support regex. Check that file download tracking is enabled.
The Colorbox module must be installed and enabled for this feature to work. The checkbox is disabled when Colorbox is not available.
The Search module must be enabled. Additionally, configure your Google Analytics property to use 'search' as the query parameter in the View Settings.
Ensure 'Multiple top-level domains' is selected as the domain mode and all domains are listed in the cross-domains textarea, one per line. All domains must use the same GA property ID.
Check that users have the 'Opt-in or out of tracking' permission and that user account mode is not set to 'No customization allowed'. Users can then find the option on their account edit page.
Certain tokens containing personally identifiable information (usernames, emails, UIDs) are blocked to comply with Google Analytics Terms of Service Section 7. Use alternative tokens that don't expose PII.
Security Notes 7
- Custom JavaScript snippet fields are protected by a separate permission ('Add JavaScript snippets') to prevent XSS attacks from unprivileged users
- Tokens containing personally identifiable information (usernames, email addresses, user IDs) are automatically blocked in custom dimensions to comply with Google Analytics Terms of Service
- User ID tracking uses HMAC-based cryptographic hashing with the site's private key, ensuring the actual user ID is never transmitted to Google
- The 'Use PHP for tracking visibility' permission is marked as restricted and the feature is deprecated - avoid using PHP code for visibility rules
- IP anonymization is enabled by default for privacy compliance, though GA4 anonymizes IPs automatically regardless of this setting
- When local caching is enabled, the JavaScript file is stored in the public files directory - ensure your server is configured securely
- Review the file extensions list if you have sensitive document types that should not be tracked