Skip to content

Instantly share code, notes, and snippets.

@philippgitpush
Last active June 5, 2024 18:54
Show Gist options
  • Save philippgitpush/5b941552eb357218262ed38f8038d170 to your computer and use it in GitHub Desktop.
Save philippgitpush/5b941552eb357218262ed38f8038d170 to your computer and use it in GitHub Desktop.
Userscript that changes X's (Formerly Twitter) video player UX to the browser's default and adds volume control memory
// ==UserScript==
// @name Enhanced X Video Player
// @version 1.0.1
// @description Enhance X video player with volume control memory.
// @author philippgitpush
// @match https://x.com/*
// @grant none
// ==/UserScript==
(() => {
'use strict';
let lastVolume = 1;
const body = document.body;
if (body) {
const observer = new MutationObserver(() => {
const videoComponents = document.body.querySelectorAll('div[data-testid="videoComponent"]:not(.enhanced-video)');
videoComponents.forEach(function(component) {
if (component) {
component.classList.add("enhanced-video");
setTimeout(() => replacePlayer(component), 100);
}
});
});
observer.observe(body, { subtree: true, childList: true });
}
const replacePlayer = component => {
const video = component.querySelector("video");
if (video) {
enhanceVideo(video);
component.appendChild(video);
}
};
const enhanceVideo = video => {
video.controls = true;
video.removeAttribute("disablepictureinpicture");
video.addEventListener("click", handleClick);
video.volume = lastVolume;
};
const handleClick = event => {
event.preventDefault();
const video = event.currentTarget;
video.play();
setTimeout(() => {
video.muted = false;
video.volume = lastVolume;
}, 0);
const handleMute = e => {
if (e.target.muted) {
e.target.muted = false;
e.target.volume = lastVolume;
}
e.currentTarget.removeEventListener("volumechange", handleMute);
};
event.currentTarget.addEventListener("volumechange", handleMute);
event.currentTarget.removeEventListener("click", handleClick);
};
setInterval(() => {
for (const video of document.getElementsByTagName("video")) {
if (video.muted) {
video.muted = false;
video.volume = lastVolume;
} else {
lastVolume = video.volume;
}
}
}, 100);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment