Block autoplay and require direct user interaction to play media
当前为
// ==UserScript==
// @name Disable autoplay
// @namespace https://www.androidacy.com/
// @version 1.2
// @description Block autoplay and require direct user interaction to play media
// @author Androidacy
// @include *
// @exclude https://www.google.com/adsense/new/*
// @icon https://www.androidacy.com/wp-content/uploads/cropped-cropped-cropped-cropped-New-Project-32-69C2A87-1-192x192.jpg
// @grant none
// @run-at document-end
// ==/UserScript==
(function() {
'use strict';
// Function to override the play method to require direct interaction with the media element
const overridePlayMethod = (media) => {
const originalPlay = media.play;
media.play = function() {
if (!media.hasUserInteracted) {
console.log('Autoplay prevented: Direct interaction with the media element is required to start playback.');
return Promise.reject(new Error('Playback requires direct interaction with the media element.'));
}
return originalPlay.apply(media, arguments);
};
};
// Function to pause all video and audio elements and disable autoplay
const disableAutoplay = () => {
const mediaElements = document.querySelectorAll('video, audio');
mediaElements.forEach((media) => {
media.autoplay = false;
media.pause();
media.removeAttribute('autoplay');
overridePlayMethod(media);
// Mark media as interacted with when it is clicked
media.addEventListener('click', () => {
media.hasUserInteracted = true;
});
});
};
// Initial run
disableAutoplay();
// Observe for dynamically added media elements
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.addedNodes.length > 0) {
disableAutoplay();
}
});
});
// Observe the entire document
observer.observe(document.body, {
childList: true,
subtree: true,
});
})();