Instagram Stories Background Playback

Allow Instagram Stories to play in the background

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name        Instagram Stories Background Playback
// @namespace   http://tampermonkey.net/
// @version     1.0
// @description Allow Instagram Stories to play in the background
// @author      HaiDang
// @match       https://*.instagram.com/*
// @icon        https://www.google.com/s2/favicons?sz=64&domain=instagram.com
// @grant       none
// @run-at      document-start
// ==/UserScript==

(function() {
    'use strict';

    const config = {
        debug: false,
        events: ['visibilitychange', 'blur', 'freeze', 'resume', 'pause'],
        checkInterval: 500,
        videoSelectors: [

            'video[class*="Story"]',
            'video[class*="stories"]',
            'video[class*="Reel"]',
            'video[class*="reels"]',
            'video[class*="Video"]',
            'video._aa63'
        ]
    };

    const logger = {
        log: (message) => {
            if (config.debug) {
                console.log(`[IG Stories Background] ${message}`);
            }
        },
        error: (message) => {
            if (config.debug) {
                console.error(`[IG Stories Background] Error: ${message}`);
            }
        }
    };

    const handleEvent = (evt) => {
        logger.log(`${evt.type} event intercepted`);
        evt.stopImmediatePropagation();
    };

    const ensureVideoPlaying = () => {
        const videoElements = config.videoSelectors
            .map(selector => [...document.querySelectorAll(selector)])
            .flat();

        videoElements.forEach((video) => {
            if (video.paused && !video.ended) {
                video.play()
                    .then(() => logger.log('Video resumed successfully'))
                    .catch((err) => logger.error(`Play failed: ${err.message}`));
            }

            video.controls = true;
            video.onpause = null;
            video.onblur = null;
            video.onfocus = null;
        });
    };

    const initEventListeners = () => {
        config.events.forEach((eventName) => {
            document.addEventListener(eventName, handleEvent, {
                capture: true,
                passive: false
            });

            window.addEventListener(eventName, handleEvent, {
                capture: true,
                passive: false
            });
        });
    };

    const initVideoObserver = () => {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                if (mutation.addedNodes.length > 0) {
                    ensureVideoPlaying();
                }
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    };

    const init = () => {
        logger.log('Initializing Instagram background playback script');

        initEventListeners();

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initVideoObserver);
        } else {
            initVideoObserver();
        }

        setInterval(ensureVideoPlaying, config.checkInterval);
    };

    init();
})();