如何拦截STOP CASTING操作以在接收器关闭前执行AJAX分析请求?
Great question! There isn't a dedicated "STOP_CASTING interceptor" in the Chromecast SDK, but there are reliable ways to fire your analytics AJAX request between the user tapping "STOP CASTING" and the receiver app actually shutting down. Let's walk through the most effective approaches:
1. Listen for Session Termination Events in the Receiver
When a user initiates STOP CASTING, the sender triggers a session end request that the receiver can detect via the SESSION_ENDED event. The key here is to ensure your analytics request completes even as the receiver prepares to shut down—use the keepalive flag with fetch to let the browser finish the request after the page starts unloading.
Here's a receiver-side code example:
const castReceiverContext = cast.framework.CastReceiverContext.getInstance(); castReceiverContext.addEventListener(cast.framework.events.EventType.SESSION_ENDED, (event) => { // Fire analytics request with keepalive to ensure it completes fetch('/your-analytics-endpoint', { method: 'POST', body: JSON.stringify({ sessionId: event.sessionId, timestamp: Date.now() }), headers: { 'Content-Type': 'application/json' }, keepalive: true // Critical: prevents the browser from canceling the request }).catch(err => console.error('Analytics request failed:', err)); }); castReceiverContext.start();
Note:
- The
keepaliveflag has a payload limit of ~64KB, so keep your analytics data concise. - This works even if you don't control the sender (e.g., using the default Chrome cast sender).
2. Send a Custom Analytics Message From the Sender (Most Reliable)
If you control the sender application (like a custom web app), you can add a deliberate step: first send a custom message to the receiver to trigger the analytics request, then initiate the STOP CASTING action. This gives you full control over the timing, ensuring the request starts before the session terminates.
Sender-side code:
const castContext = cast.framework.CastContext.getInstance(); const currentSession = castContext.getCurrentSession(); // First, send analytics trigger to receiver currentSession.sendMessage('urn:x-cast:com.your.app.analytics', { action: 'logStopCast' }) .then(() => { // Once message is sent, proceed to stop casting return castContext.stopCasting(); }) .catch(err => { console.error('Failed to send analytics message:', err); // Fallback: still stop casting even if analytics fails castContext.stopCasting(); });
Receiver-side code:
const castReceiverContext = cast.framework.CastReceiverContext.getInstance(); // Create a custom message bus for analytics const analyticsBus = castReceiverContext.getMessageBus('urn:x-cast:com.your.app.analytics'); analyticsBus.onMessage = (event) => { if (event.data.action === 'logStopCast') { // Fire your analytics request fetch('/your-analytics-endpoint', { method: 'POST', body: JSON.stringify({ senderId: event.senderId, sessionDuration: Date.now() - sessionStartTime // Example metric }), headers: { 'Content-Type': 'application/json' } }).then(() => { // Optional: send confirmation back to sender analyticsBus.send(event.senderId, { status: 'analyticsLogged' }); }).catch(err => console.error('Analytics request failed:', err)); } }; castReceiverContext.start();
3. Use the beforeunload Event (Fallback)
As a last resort, you can listen to the receiver page's beforeunload event. However, browsers often cancel asynchronous requests during unload, so again, use keepalive or a synchronous XMLHttpRequest (though sync XHR is generally discouraged, it's acceptable here for the narrow use case):
window.addEventListener('beforeunload', (event) => { // Or use fetch with keepalive (preferred over sync XHR) fetch('/your-analytics-endpoint', { method: 'POST', body: JSON.stringify({ event: 'castStopped' }), keepalive: true }); });
Key Takeaways:
- Custom sender message: The most reliable approach, as you control the order of operations.
- SESSION_ENDED event with keepalive: Best for when you don't control the sender.
- beforeunload: Fallback, but less consistent across devices.
内容的提问来源于stack exchange,提问作者skl

