fix: prevent initial playback when autoplay is disabled (#1461)
Problem
When Autoplay is disabled in ImprovedTube settings, opening a YouTube video in a new tab or via the address bar causes the video to play for ~1 second before being paused. This brief playback:
- Adds the video to watch history (the core user complaint)
- Defeats the purpose of the autoplay-disable setting
- Does not occur on internal YouTube navigation (clicking video links within YouTube)
Root Cause
The existing fix hooks HTMLMediaElement.prototype.play() and calls player.pauseVideo() immediately. However, on fresh page loads (new tab / address bar navigation), there is a race condition: YouTube's player begins rendering frames before our pause takes effect. The ~1 second gap is enough for YouTube to register the video as "played" and add it to watch history.
Internal navigation works correctly because the player element (and our hook) is already initialized from the previous page.
Solution
Added a playing event safety net that catches any playback slipping through the play() interception gap:
New: ImprovedTube.autoplayPlayingHandler()
- Fires on the native HTMLMediaElement
playingevent - Checks all three autoplay-disable scenarios: player, playlist, channel trailer
- Pauses immediately if autoplay is disabled AND user has not interacted
- Self-removing listener (fires once, then detaches — zero ongoing overhead)
Modified: ImprovedTube.playerOnPlay()
- Registers the
playingsafety-net listener alongside the existingplay()interception - Only attached when autoplay conditions are met (no impact when autoplay is enabled)
Changes
| File | Change |
|---|---|
js&css/web-accessible/functions.js |
+58 lines (new handler), -30 lines (reformatted) |
Testing
- ✅ All 61 existing unit tests pass (
npm test) - Manual verification steps:
- Enable "Autoplay" -> OFF in ImprovedTube settings
- Open any YouTube video in a new tab -> video should not play at all
- Navigate via address bar -> same result
- Internal navigation (clicking video links) -> still works correctly
- Normal playback (autoplay ON) -> no regression
Fixes #1461
hi! @jiangyj545 please mark up ("disclose") LLM usage exactly to collaborate efficiently.
Hi @ImprovedTube2, thanks for the review!
LLM Disclosure: This PR was authored with assistance from AI coding tools (Claude/Hermes agent). I analyzed the ImprovedTube codebase, used AI to generate the initial implementation for the autoplay fix in improvedtube.js, then reviewed and refined it before submission.
Happy to answer questions about implementation details!