Skip to content

Conversation

@chihsuan
Copy link
Member

@chihsuan chihsuan commented Nov 12, 2025

Fixes WOOA7S-661

Proposed changes:

  • Implement navigator.sendBeacon() as the primary method for sending analytics events
  • Add graceful fallback to fetch() with keepalive: true option for browsers without beacon support
  • Pass REST API endpoint URL from server-side to handle plain permalinks correctly (using rest_url())
  • Replace @wordpress/api-fetch dependency with native fetch() API for simpler, more portable code
  • Remove unused constants (API_NAMESPACE, API_ENDPOINT) as endpoint is now fully server-controlled

Other information:

  • Have you written new tests for your changes, if applicable? - No tests added (deferred to future work as agreed)
  • Have you checked the E2E test CI results, and verified that your changes do not break them?
  • Have you tested your changes on WordPress.com, if applicable?

Does this pull request change what data or activity we track or use?

No. This PR only changes how events are sent to the server, not what data is tracked. The tracking endpoint, event payloads, and data handling remain unchanged.

Testing instructions:

Prerequisites:

  1. WooCommerce site with Jetpack connected
  2. Enable proxy tracking: add_filter('woocommerce_analytics_experimental_proxy_tracking_enabled', '__return_true'); OR enable WooCommerce Analytics plugin

Test 1: Verify Beacon API is used

  1. Visit a product page on the WooCommerce site
  2. Open DevTools Console and run: localStorage.setItem('debug', 'wc-analytics:*')
  3. Reload the page
  4. In Console, look for: "Sent X events via Beacon API"
  5. In Network tab, you should not see fetch/XHR requests to /wp-json/woocommerce-analytics/v1/track but can see requests in All tab.
Screenshot 2025-11-12 at 15 11 42 Screenshot 2025-11-12 at 15 11 13

Test 2: Verify fallback for browsers without beacon

  1. Open DevTools Console and tick Preserve log checkbox
  2. Log in to the WooCommerce site and go to my account page
  3. Run: navigator.sendBeacon = undefined (simulates old browser)
  4. Click "Log out"
  5. Console should show: "Failed to send events via Beacon API, falling back to fetch with keepalive"
  6. Network tab should show POST request to /wp-json/woocommerce-analytics/v1/track with keepalive flag
  7. Events should still be tracked successfully

Key Benefits:

  • Guaranteed event delivery on page unload (beacon survives navigation)
  • Mobile-friendly (better iOS Safari support)
  • Plain permalink support (server controls URL format)
  • Bot filtering (sophisticated bots disable beaconing)
  • Simpler codebase (one less dependency)

chihsuan and others added 2 commits November 12, 2025 15:09
…fallback

Implements navigator.sendBeacon() as the primary method for sending analytics events, with graceful fallback to fetch() with keepalive option. This ensures reliable event delivery, especially during page unload scenarios where traditional async requests may be cancelled by the browser.

Changes:
- Add sendEventsViaBeacon() method using navigator.sendBeacon API
- Replace @wordpress/api-fetch with native fetch() + keepalive option
- Pass REST API endpoint URL from server to handle plain permalinks correctly
- Add trackEndpoint to wcAnalytics config in PHP (using rest_url())
- Remove @wordpress/api-fetch dependency from package.json
- Remove unused API_NAMESPACE and API_ENDPOINT constants

Benefits:
- Guaranteed event delivery on page unload (browser queues beacon requests)
- Better mobile browser support (especially iOS Safari)
- Works correctly with plain permalinks
- Filters out sophisticated bots that disable beaconing APIs
- Simpler codebase with native Web APIs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@chihsuan chihsuan changed the title Analytics: Use Beacon API for reliable event tracking with keepalive fallback WooCommerce Analytics: Use Beacon API for reliable event tracking with keepalive fallback Nov 12, 2025
@chihsuan chihsuan changed the title WooCommerce Analytics: Use Beacon API for reliable event tracking with keepalive fallback WooCommerce Analytics: Use Beacon API for reliable event tracking with fallback Nov 12, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Nov 12, 2025

Are you an Automattician? Please test your changes on all WordPress.com environments to help mitigate accidental explosions.

  • To test on WoA, go to the Plugins menu on a WoA dev site. Click on the "Upload" button and follow the upgrade flow to be able to upload, install, and activate the Jetpack Beta plugin. Once the plugin is active, go to Jetpack > Jetpack Beta, select your plugin (Jetpack or WordPress.com Site Helper), and enable the wooa7s-661-use-beaconing-apis-for-sending-tracking-events branch.
  • To test on Simple, run the following command on your sandbox:
bin/jetpack-downloader test jetpack wooa7s-661-use-beaconing-apis-for-sending-tracking-events
bin/jetpack-downloader test jetpack-mu-wpcom-plugin wooa7s-661-use-beaconing-apis-for-sending-tracking-events

Interested in more tips and information?

  • In your local development environment, use the jetpack rsync command to sync your changes to a WoA dev blog.
  • Read more about our development workflow here: PCYsg-eg0-p2
  • Figure out when your changes will be shipped to customers here: PCYsg-eg5-p2

@github-actions
Copy link
Contributor

github-actions bot commented Nov 12, 2025

Thank you for your PR!

When contributing to Jetpack, we have a few suggestions that can help us test and review your patch:

  • ✅ Include a description of your PR changes.
  • ✅ Add a "[Status]" label (In Progress, Needs Review, ...).
  • ✅ Add a "[Type]" label (Bug, Enhancement, Janitorial, Task).
  • ✅ Add testing instructions.
  • ✅ Specify whether this PR includes any changes to data or privacy.
  • ✅ Add changelog entries to affected projects

This comment will be updated as you work on your PR and make changes. If you think that some of those checks are not needed for your PR, please explain why you think so. Thanks for cooperation 🤖


Follow this PR Review Process:

  1. Ensure all required checks appearing at the bottom of this PR are passing.
  2. Make sure to test your changes on all platforms that it applies to. You're responsible for the quality of the code you ship.
  3. You can use GitHub's Reviewers functionality to request a review.
  4. When it's reviewed and merged, you will be pinged in Slack to deploy the changes to WordPress.com simple once the build is done.

If you have questions about anything, reach out in #jetpack-developers for guidance!

@github-actions github-actions bot added the [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. label Nov 12, 2025
@chihsuan chihsuan requested a review from Copilot November 12, 2025 07:22
@chihsuan chihsuan added [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it [Status] Needs Review This PR is ready for review. and removed [Status] Needs Author Reply We need more details from you. This label will be auto-added until the PR meets all requirements. labels Nov 12, 2025
Copilot finished reviewing on behalf of chihsuan November 12, 2025 07:26
@chihsuan chihsuan requested review from a team November 12, 2025 07:26
@chihsuan chihsuan self-assigned this Nov 12, 2025
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR improves the reliability of WooCommerce Analytics event tracking by implementing the Beacon API as the primary transport method with a fetch-based fallback, and removes the @wordpress/api-fetch dependency in favor of native browser APIs.

Key Changes:

  • Implements navigator.sendBeacon() for guaranteed event delivery during page unload/navigation
  • Adds fallback to native fetch() with keepalive: true for browsers without Beacon API support
  • Moves REST API endpoint URL generation to server-side using rest_url() for better plain permalink support

Reviewed Changes

Copilot reviewed 5 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/client/types/global.d.ts Adds trackEndpoint property to window.wcAnalytics interface
src/client/constants.ts Removes unused API_NAMESPACE and API_ENDPOINT constants now that endpoint is server-controlled
src/client/api-client.ts Replaces @wordpress/api-fetch with Beacon API and native fetch, adds new sendEventsViaBeacon method
src/class-universal.php Injects REST API tracking endpoint URL via rest_url() into client-side wcAnalytics object
package.json Removes @wordpress/api-fetch dependency
changelog/wooa7s-661-use-beaconing-apis-for-sending-tracking-events Adds changelog entry for the changes
pnpm-lock.yaml Updates lockfile to reflect dependency removal
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

…lability

This update adds a check for the existence of the trackEndpoint in the wcAnalytics configuration before attempting to send events. If the trackEndpoint is not available, a debug message is logged, and the event sending process is halted. The fallback mechanism to fetch with keepalive is retained for cases where the Beacon API fails, ensuring robust event delivery.

Changes:
- Added a conditional check for window.wcAnalytics?.trackEndpoint
- Updated debug logging for better clarity on event sending status
@jp-launch-control
Copy link

jp-launch-control bot commented Nov 12, 2025

Code Coverage Summary

Coverage changed in 1 file.

File Coverage Δ% Δ Uncovered
projects/packages/woocommerce-analytics/src/class-universal.php 0/368 (0.00%) 0.00% 1 ❤️‍🩹

Full summary · PHP report · JS report

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Feature] WooCommerce Analytics [Package] WooCommerce Analytics Enhanced analytics for WooCommerce users [Status] Needs Review This PR is ready for review. [Type] Enhancement Changes to an existing feature — removing, adding, or changing parts of it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants