Disable autoplay

Block autoplay and require direct user interaction to play media

当前为 2024-08-25 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==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,
    });

})();