Real-Time Document Co-Reading: How to Sync Reading Position
In this article
To sync reading position during real-time document co-reading in a browser, you must continuously transmit each participant's current scroll position (or a percentage of the document) to a shared state, and then have each client scroll to the latest received position—usually with a brief pause to avoid feedback loops. This is typically done using WebSockets or a real-time database like Firebase, with a small debounce delay to prevent excessive updates.
Background: Why Co-Reading is Different from Co-Editing
Co-editing tools (like Google Docs) focus on cursor placement and text changes. Co-reading, however, is about keeping everyone on the same visual page—literally. When two people read a long article, a PDF, or a legal document together, they want to know where the other person is looking. This is not just a convenience; it's essential for remote book clubs, collaborative research, customer support screen-sharing, or even online education where a teacher follows a student's progress.
The challenge is that reading position is a continuous value (scroll offset) that changes rapidly, unlike discrete edits. Sending every pixel change would flood the network. So, the core problem is not just transmitting data, but doing so efficiently and without causing a 'scroll war' where two users constantly override each other.
How the Sync Mechanism Works
There are three main components to any reading-position sync system:
- Capture: Listen to the
scrollevent on the document or a container element. Compute the current position as a normalized value—for example,scrollTop / (scrollHeight - clientHeight)—which gives a percentage from 0 to 1. This is better than raw pixels because it works across different screen sizes and zoom levels. - Transmit: Send this percentage to a central server or directly to peers. Use a WebSocket for low latency, or a service like Firebase Realtime Database that handles synchronization automatically. To avoid flooding, throttle updates: send at most every 100-200 milliseconds, or only when the position changes by more than 0.5%.
- Apply: On the receiving side, listen for incoming position updates. When one arrives, scroll the local view to that percentage. To prevent a feedback loop (where your own update comes back and scrolls you), include a unique user ID in the message and ignore messages from yourself.
Here's a simplified example of the capture and transmit logic in JavaScript:
let lastSent = 0;
const container = document.getElementById('reader');
container.addEventListener('scroll', () => {
const now = Date.now();
if (now - lastSent < 150) return; // throttle
lastSent = now;
const max = container.scrollHeight - container.clientHeight;
const percent = max > 0 ? container.scrollTop / max : 0;
socket.send(JSON.stringify({ type: 'position', user: userId, value: percent }));
});
Choosing the Right Sync Technology
Your choice depends on the scale and complexity of your project:
- WebSockets (Socket.IO, ws): Best for real-time, low-latency, and custom control. You manage the server and state yourself. Ideal for a small group (2-10 users) where you need fine-grained control over throttling and conflict resolution.
- Firebase Realtime Database / Firestore: Great for quick prototyping and scaling. You can store the position in a document and listen for changes. No server code needed. However, be mindful of write costs if you update too frequently.
- Yjs or ShareDB: These are CRDT-based libraries designed for collaborative editing. They can also handle presence data (like cursor positions) and are a good choice if you plan to add co-editing later.
- WebRTC DataChannels: For peer-to-peer without a central server, but you'll need a signaling server to establish connections, and it's more complex for larger groups.
Common Problems and How to Solve Them
Even with a solid implementation, you'll encounter these issues:
- Scroll Feedback Loop: When A's update scrolls B, B's scroll event fires and sends a new update back to A. Solve by ignoring incoming updates that match your own user ID, and by using a 'silent scroll' flag that suppresses sending while applying an external update.
- Different Screen Sizes: A percentage works well, but if one user has a huge monitor and the other a phone, the same percentage may show different content. Consider syncing based on the top line of text (using a text offset) instead of pixel percentage. This is more complex but more accurate.
- Fast Scrolling: If a user flicks the scrollbar, you might miss intermediate positions. Use a larger throttle interval (e.g., 300ms) and always send the latest position on the 'scrollend' event if available.
- Document Resize: When images load or window resizes, the scrollHeight changes, making percentages jump. Recalculate the position on resize and send a corrected update.
Comparison: Scroll Sync vs. Content Sync
There are two philosophies for co-reading:
- Scroll Sync: Everyone's viewport is at the same scroll offset. Simple, but fails when content wraps differently (e.g., a narrow window makes text taller).
- Content Sync: Everyone sees the same line of text at the top of their viewport. This is what many e-readers do. It requires mapping a position in the text (like a character offset) to a scroll position on each device. This is more robust but requires the document to be identical across all clients.
For a simple blog post, scroll sync is fine. For a PDF or a fixed-layout document, content sync is better because the layout is identical. For a responsive HTML page, content sync is hard; you'd need to calculate which text node is at the top and send its path.
Cost and Performance Considerations
If you're using a third-party service like Firebase, the cost is based on reads/writes. Sending a position every 200ms per user could incur significant costs for a large user base. To reduce costs:
- Increase the throttle interval to 500ms or 1 second.
- Only send updates when the user is actively scrolling (not continuously).
- Use a 'heartbeat' that sends the position every 5 seconds even if not scrolling, so late joiners can catch up.
For a self-hosted WebSocket server, the cost is mainly bandwidth. A single position message is tiny (less than 100 bytes), so even 10 updates per second per user is negligible for a small group.
Frequently Asked Questions
Can I sync reading position without a server?
Yes, using WebRTC DataChannels for peer-to-peer communication. You'll need a signaling server to exchange connection info initially, but after that, data flows directly between browsers. This works well for 2-5 users but becomes complex with more.
How do I avoid scrolling when I don't want to follow?
Add a 'follow' toggle. When off, ignore incoming position updates. When on, scroll to the latest position. This is a common UI pattern in collaborative tools.
What if one user is on a mobile phone and the other on a desktop?
Percentage-based sync will still work, but the content shown may differ. For a better experience, use content sync (based on text position) or encourage both users to use similar viewport sizes. Alternatively, you can render the document in a fixed-width container on both devices.
Does this work with PDFs in the browser?
Yes, if you're using a PDF viewer like PDF.js. You can listen to the scroll event of the PDF container and sync the page number and scroll offset within the page. Many online co-reading tools do exactly this.
How do I handle late joiners?
When a new user joins, have the server send the latest known position (or the position of the most recently active user) to the new user. The new user then scrolls to that position. Store the latest position in memory or a database.
Is it better to use a library or build from scratch?
If you need a quick solution, use a library like Yjs (with its presence feature) or a service like Firebase. If you need full control over the algorithm and have specific performance needs, building from scratch with WebSockets is feasible and educational.