"view replies" auto expander

click on "view replies (500)" and it will click on the same button until all replies open.

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

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

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         "view replies" auto expander
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  click on "view replies (500)" and it will click on the same button until all replies open.
// @author       goodwin64
// @match        *://instagram.com/*
// @match        *://www.instagram.com/*
// @namespace    instagram.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const markedElements = new Set();

    function listenToExpandClicks() {
      [...document.getElementsByTagName('span')]
        .filter(el => el.innerText.toLowerCase().includes('view'))
        .forEach(el => {
          if (!markedElements.has(el)) {
            el.addEventListener('click', handleViewRepliesClick);
            markedElements.add(el);
          }
        });
    }
    
    function howMuchRepliesLeft(str) {
      const repliesCountMatch = str.match(/.*\((\d*)\)/)
      return repliesCountMatch ? Number(repliesCountMatch[1]) : 0;
    }
    
    function handleViewRepliesClick() {
      clickIfExpandable(this);
    }
    
    function clickIfExpandable(el) {
      const repliesLeft = howMuchRepliesLeft(el.innerText);
      if (repliesLeft > 0) {
        el.click();
        setTimeout(() => {
          clickIfExpandable(el);
        }, 1000);
      } else {
        el.removeEventListener('click', handleViewRepliesClick);
        markedElements.delete(el);
      }
    }
    
    setInterval(listenToExpandClicks, 3000);
})();