X/Twitter Image Easy Close

X/Twitter Image Easy Close functionality

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

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

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

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

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

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         X/Twitter Image Easy Close
// @namespace    https://github.com/BD9Max
// @version      1.0
// @description  X/Twitter Image Easy Close functionality
// @author       krbd9max
// @match        https://twitter.com/*
// @match        https://x.com/*
// @license      MIT
// @grant        none
// @icon         https://upload.wikimedia.org/wikipedia/commons/c/ce/X_logo_2023.svg
// ==/UserScript==

(function() {
    'use strict';

    // Function to trigger the native Twitter close action
    const closeImageOverlay = () => {
        const closeButton = document.querySelector('[data-testid="app-bar-close"]');
        if (closeButton) {
            closeButton.click();
        } else {
            // Fallback: If the button isn't found, use the browser back action to exit the photo URL
            window.history.back();
        }
    };

    document.addEventListener('click', (e) => {
        // Only run if we are currently looking at a photo/media overlay
        if (window.location.pathname.includes('/photo/')) {
            
            // Check if the click is on an interactive UI element (Like, Retweet, Reply buttons)
            // We exclude these so you can still interact with the post without it closing.
            const isControl = e.target.closest('[role="button"]') || 
                              e.target.closest('[role="menuitem"]') ||
                              e.target.closest('[data-testid="KeybindLayer"]');

            if (!isControl) {
                // Prevent the default Twitter click behavior and close the overlay
                e.stopPropagation();
                closeImageOverlay();
            }
        }
    }, true); // Use capture phase to intercept the click immediately
})();