Skip to content

Instantly share code, notes, and snippets.

@renestalder
Last active June 16, 2026 11:23
Show Gist options
  • Select an option

  • Save renestalder/c5b77635bfbec8f94d28 to your computer and use it in GitHub Desktop.

Select an option

Save renestalder/c5b77635bfbec8f94d28 to your computer and use it in GitHub Desktop.
Unfollow all on Facebook

Facebook: Unfollow people and pages

See comments section for more up-to-date versions of the script. The original script is from 2014 and will not work as is.

  1. Open news feed preferences on your Facebook menu (browser)
  2. Click people or pages
  3. Scroll down (or click see more) until your full list is loaded
  4. Run the script in your browser console

Facebook will block this feature for you while you use it, depending on how much entities you try to unfollow. It automatically unblocks in a couple of hours and you will be able to continue.

var unfollowButtons = document.querySelectorAll('[data-followed="1"]'); for(var i=0;i<unfollowButtons.length;i++){ unfollowButtons[i].click(); } alert(unfollowButtons.length+' people are now unfollowed! ');
@daviddonatoiii

Copy link
Copy Markdown

Any updates? script isn't working anymore >.<

@matsyui

matsyui commented Oct 30, 2025

Copy link
Copy Markdown

No update?

@ixus36900

Copy link
Copy Markdown

Partial Solution to Unfollow Contacts on Facebook

I've been using a partial solution these days to unfollow contacts on Facebook. So far, I've managed to unfollow over 1,800 contacts, but I still have some left.

Steps:

Install Tampermonkey Extension: Install the Tampermonkey extension on Chrome (I recommend using Chrome).

https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en

Enable User Scripts: Go to the application manager, find Tampermonkey, click on "Details," and enable the "Allow user scripts" option.

Create a New Script: Click on the Tampermonkey icon, select "Create a new script," and replace the example code with the following:

// ==UserScript==
// @name         Unfollow FB
// @namespace    http://tampermonkey.net/
// @version      1.8
// @description  Versión estable y optimizada con esperas híbridas, contadores y scroll inteligente.
// @author       D.
// @match        https://www.facebook.com/*/following*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // --- CONFIGURACIÓN ---
    const INTERVALO_ENTRE_ACCIONES = 3500; // 3.5 segundos entre perfiles (un buen equilibrio).
    const PAUSA_CORTA_FIJA = 1500; // Pausa fija para sub-menús.
    const TIMEOUT_ESPERA_HOVER = 4000; // Tiempo máximo para que aparezca el hover principal.

    // --- ESTADO Y CONTADORES ---
    let perfilesProcesados = new Set();
    let contadorExitos = 0;
    let contadorFallos = 0;
    let intentosScrollSinExito = 0;
    const MAX_INTENTOS_SCROLL = 3;
    let procesoActivo = false;

    // --- ELEMENTOS DE LA INTERFAZ ---
    let panelInfo, controlButton, exitosDisplay, fallosDisplay;

    // --- FUNCIONES AUXILIARES ---
    function esperar(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function waitForElement(selector, timeout = TIMEOUT_ESPERA_HOVER) {
        const startTime = Date.now();
        while (Date.now() - startTime < timeout) {
            const element = document.querySelector(selector);
            if (element) return element;
            await esperar(100);
        }
        return null;
    }

    function actualizarUI() {
        if (exitosDisplay) exitosDisplay.textContent = `Éxitos: ${contadorExitos}`;
        if (fallosDisplay) fallosDisplay.textContent = `Fallos: ${contadorFallos}`;
    }

    function detenerProceso(mensaje) {
        procesoActivo = false;
        controlButton.textContent = 'Proceso Detenido';
        controlButton.style.backgroundColor = '#888';
        controlButton.disabled = true;
        console.log(`[Control] ${mensaje}`);
    }

    // --- LÓGICA DE "DEJAR DE SEGUIR"---
    async function intentarDejarDeSeguir(hoverContainer) {
        // Escenario 1
        const botonDejarSeguirDirecto = hoverContainer.querySelector('div[role="button"][aria-label="Dejar de seguir"]');
        if (botonDejarSeguirDirecto) {
            console.log("[Info] Escenario 1: 'Dejar de seguir' directo.");
            botonDejarSeguirDirecto.click();
            return true;
        }

        // Escenario 2
        const botonSiguiendo = hoverContainer.querySelector('div[role="button"][aria-label="Siguiendo"]');
        if (botonSiguiendo) {
            console.log("[Info] Escenario 2: Botón 'Siguiendo'.");
            botonSiguiendo.click();
            await esperar(PAUSA_CORTA_FIJA); // Pausa fija para estabilidad
            const botonDejarSeguirMenu = Array.from(document.querySelectorAll('div[role="menuitem"]')).find(el => el.textContent.includes('Dejar de seguir'));
            if (botonDejarSeguirMenu) {
                botonDejarSeguirMenu.click();
                return true;
            }
        }

        // Escenario 3
        const botonMasOpciones = hoverContainer.querySelector('div[role="button"][aria-label*="Opciones"]');
        if (botonMasOpciones) {
            console.log("[Info] Escenario 3: Botón '...'.");
            botonMasOpciones.click();
            await esperar(PAUSA_CORTA_FIJA); // Pausa fija para estabilidad
            const botonDejarSeguirMenu = Array.from(document.querySelectorAll('div[role="menuitem"]')).find(el => el.textContent.includes('Dejar de seguir'));
            if (botonDejarSeguirMenu) {
                botonDejarSeguirMenu.click();
                return true;
            }
        }

        return false;
    }

    // --- LÓGICA PRINCIPAL ---
    async function procesarUnPerfil() {
        const contenedoresDePerfil = document.querySelectorAll('div.x78zum5.x1q0g3np.x1a02dak.x1qughib > div');
        let perfilEncontradoParaProcesar = false;

        for (const perfil of contenedoresDePerfil) {
            const enlaceElemento = perfil.querySelector('a[href*="facebook.com/"]');
            if (!enlaceElemento || perfilesProcesados.has(enlaceElemento.href)) continue;

            perfilEncontradoParaProcesar = true;
            intentosScrollSinExito = 0;
            console.log(`[Acción] Procesando: ${enlaceElemento.href}.`);

            perfil.scrollIntoView({ behavior: 'smooth', block: 'center' });
            perfil.style.border = "2px solid red";
            await esperar(500);

            enlaceElemento.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true }));

            const hoverContainer = await waitForElement('div[aria-label="Vista previa del enlace"]');

            if (!hoverContainer) {
                console.error("[Fallo] No se encontró el pop-up del hover (timeout).");
                contadorFallos++;
                perfil.style.border = "2px solid orange";
            } else {
                const exito = await intentarDejarDeSeguir(hoverContainer);

                if (exito) {
                    console.log("[Éxito] Acción de 'dejar de seguir' completada.");
                    contadorExitos++;
                    perfil.style.border = "2px solid green";
                } else {
                    console.warn("[Fallo] Se abrió el hover, pero no se encontró ninguna acción válida.");
                    contadorFallos++;
                    perfil.style.border = "2px solid orange";
                }

                await esperar(500);

                const botonCerrar = document.querySelector('div[role="button"][aria-label="Cerrar"]');
                if (botonCerrar) botonCerrar.click();
            }

            actualizarUI();
            perfilesProcesados.add(enlaceElemento.href);
            break;
        }

        if (!perfilEncontradoParaProcesar && contenedoresDePerfil.length > 0) {
            intentosScrollSinExito++;
            console.log(`[Info] No hay perfiles nuevos. Intento de scroll ${intentosScrollSinExito}/${MAX_INTENTOS_SCROLL}.`);
            if (intentosScrollSinExito >= MAX_INTENTOS_SCROLL) {
                detenerProceso("Proceso completado: Se ha llegado al final de la lista.");
            } else {
                window.scrollTo(0, document.body.scrollHeight);
            }
        }
    }

    async function buclePrincipal() {
        while (procesoActivo) {
            await procesarUnPerfil();
            await esperar(INTERVALO_ENTRE_ACCIONES);
        }
    }

    // --- INICIO Y CREACIÓN DE INTERFAZ ---
    function inicializar() {
        panelInfo = document.createElement('div');
        panelInfo.style.cssText = 'position: fixed; top: 100px; right: 20px; z-index: 9998; background: rgba(255, 255, 255, 0.9); padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-family: Arial, sans-serif;';

        exitosDisplay = document.createElement('div');
        exitosDisplay.style.cssText = 'color: green; font-weight: bold;';

        fallosDisplay = document.createElement('div');
        fallosDisplay.style.cssText = 'color: red; font-weight: bold; margin-top: 5px;';

        panelInfo.appendChild(exitosDisplay);
        panelInfo.appendChild(fallosDisplay);
        document.body.appendChild(panelInfo);

        controlButton = document.createElement('button');
        controlButton.textContent = 'Iniciar Proceso';
        controlButton.style.cssText = 'position: fixed; top: 160px; right: 20px; z-index: 9999; padding: 10px 20px; background-color: #4267B2; color: white; border: none; border-radius: 5px; cursor: pointer;';
        document.body.appendChild(controlButton);

        actualizarUI();

        controlButton.addEventListener('click', () => {
            if (procesoActivo) {
                procesoActivo = false;
                controlButton.textContent = 'Iniciar Proceso';
                controlButton.style.backgroundColor = '#4267B2';
                console.log("[Control] Proceso detenido por el usuario. Finalizará después del ciclo actual.");
            } else {
                procesoActivo = true;
                controlButton.textContent = 'Detener Proceso';
                controlButton.style.backgroundColor = '#E0245E';
                console.log(`[Control] Proceso iniciado.`);
                buclePrincipal();
            }
        });
    }

    window.addEventListener('load', inicializar);

})();

Save the Script: Click "File" > "Save" and close the window.

Run the Script: Open Facebook, replace "youruser" with your username in the following link: https://www.facebook.com/youruser/following.
This will take you to the "Following" page.

Start the Process: Click the "Iniciar Proceso" (Start Process) button on the top right corner, and the script will start unfollowing contacts one by one, displaying a counter for successful and failed unfollows.

Limitations:

Doesn't unfollow:
Favorited contacts
Groups or pages
Only unfollows contacts

Manual Intervention Required: When the script encounters a page or group, you'll need to manually close the opened window to prevent the script from crashing.

To Avoid Bans: I recommend stopping the script every 400-500 contacts.

Hope this helps!

@matsyui

matsyui commented Oct 31, 2025

Copy link
Copy Markdown

Partial Solution to Unfollow Contacts on Facebook

I've been using a partial solution these days to unfollow contacts on Facebook. So far, I've managed to unfollow over 1,800 contacts, but I still have some left.

Steps:

Install Tampermonkey Extension: Install the Tampermonkey extension on Chrome (I recommend using Chrome).

https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en

Enable User Scripts: Go to the application manager, find Tampermonkey, click on "Details," and enable the "Allow user scripts" option.

Create a New Script: Click on the Tampermonkey icon, select "Create a new script," and replace the example code with the following:

// ==UserScript==
// @name         Unfollow FB
// @namespace    http://tampermonkey.net/
// @version      1.8
// @description  Versión estable y optimizada con esperas híbridas, contadores y scroll inteligente.
// @author       D.
// @match        https://www.facebook.com/*/following*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // --- CONFIGURACIÓN ---
    const INTERVALO_ENTRE_ACCIONES = 3500; // 3.5 segundos entre perfiles (un buen equilibrio).
    const PAUSA_CORTA_FIJA = 1500; // Pausa fija para sub-menús.
    const TIMEOUT_ESPERA_HOVER = 4000; // Tiempo máximo para que aparezca el hover principal.

    // --- ESTADO Y CONTADORES ---
    let perfilesProcesados = new Set();
    let contadorExitos = 0;
    let contadorFallos = 0;
    let intentosScrollSinExito = 0;
    const MAX_INTENTOS_SCROLL = 3;
    let procesoActivo = false;

    // --- ELEMENTOS DE LA INTERFAZ ---
    let panelInfo, controlButton, exitosDisplay, fallosDisplay;

    // --- FUNCIONES AUXILIARES ---
    function esperar(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async function waitForElement(selector, timeout = TIMEOUT_ESPERA_HOVER) {
        const startTime = Date.now();
        while (Date.now() - startTime < timeout) {
            const element = document.querySelector(selector);
            if (element) return element;
            await esperar(100);
        }
        return null;
    }

    function actualizarUI() {
        if (exitosDisplay) exitosDisplay.textContent = `Éxitos: ${contadorExitos}`;
        if (fallosDisplay) fallosDisplay.textContent = `Fallos: ${contadorFallos}`;
    }

    function detenerProceso(mensaje) {
        procesoActivo = false;
        controlButton.textContent = 'Proceso Detenido';
        controlButton.style.backgroundColor = '#888';
        controlButton.disabled = true;
        console.log(`[Control] ${mensaje}`);
    }

    // --- LÓGICA DE "DEJAR DE SEGUIR"---
    async function intentarDejarDeSeguir(hoverContainer) {
        // Escenario 1
        const botonDejarSeguirDirecto = hoverContainer.querySelector('div[role="button"][aria-label="Dejar de seguir"]');
        if (botonDejarSeguirDirecto) {
            console.log("[Info] Escenario 1: 'Dejar de seguir' directo.");
            botonDejarSeguirDirecto.click();
            return true;
        }

        // Escenario 2
        const botonSiguiendo = hoverContainer.querySelector('div[role="button"][aria-label="Siguiendo"]');
        if (botonSiguiendo) {
            console.log("[Info] Escenario 2: Botón 'Siguiendo'.");
            botonSiguiendo.click();
            await esperar(PAUSA_CORTA_FIJA); // Pausa fija para estabilidad
            const botonDejarSeguirMenu = Array.from(document.querySelectorAll('div[role="menuitem"]')).find(el => el.textContent.includes('Dejar de seguir'));
            if (botonDejarSeguirMenu) {
                botonDejarSeguirMenu.click();
                return true;
            }
        }

        // Escenario 3
        const botonMasOpciones = hoverContainer.querySelector('div[role="button"][aria-label*="Opciones"]');
        if (botonMasOpciones) {
            console.log("[Info] Escenario 3: Botón '...'.");
            botonMasOpciones.click();
            await esperar(PAUSA_CORTA_FIJA); // Pausa fija para estabilidad
            const botonDejarSeguirMenu = Array.from(document.querySelectorAll('div[role="menuitem"]')).find(el => el.textContent.includes('Dejar de seguir'));
            if (botonDejarSeguirMenu) {
                botonDejarSeguirMenu.click();
                return true;
            }
        }

        return false;
    }

    // --- LÓGICA PRINCIPAL ---
    async function procesarUnPerfil() {
        const contenedoresDePerfil = document.querySelectorAll('div.x78zum5.x1q0g3np.x1a02dak.x1qughib > div');
        let perfilEncontradoParaProcesar = false;

        for (const perfil of contenedoresDePerfil) {
            const enlaceElemento = perfil.querySelector('a[href*="facebook.com/"]');
            if (!enlaceElemento || perfilesProcesados.has(enlaceElemento.href)) continue;

            perfilEncontradoParaProcesar = true;
            intentosScrollSinExito = 0;
            console.log(`[Acción] Procesando: ${enlaceElemento.href}.`);

            perfil.scrollIntoView({ behavior: 'smooth', block: 'center' });
            perfil.style.border = "2px solid red";
            await esperar(500);

            enlaceElemento.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true }));

            const hoverContainer = await waitForElement('div[aria-label="Vista previa del enlace"]');

            if (!hoverContainer) {
                console.error("[Fallo] No se encontró el pop-up del hover (timeout).");
                contadorFallos++;
                perfil.style.border = "2px solid orange";
            } else {
                const exito = await intentarDejarDeSeguir(hoverContainer);

                if (exito) {
                    console.log("[Éxito] Acción de 'dejar de seguir' completada.");
                    contadorExitos++;
                    perfil.style.border = "2px solid green";
                } else {
                    console.warn("[Fallo] Se abrió el hover, pero no se encontró ninguna acción válida.");
                    contadorFallos++;
                    perfil.style.border = "2px solid orange";
                }

                await esperar(500);

                const botonCerrar = document.querySelector('div[role="button"][aria-label="Cerrar"]');
                if (botonCerrar) botonCerrar.click();
            }

            actualizarUI();
            perfilesProcesados.add(enlaceElemento.href);
            break;
        }

        if (!perfilEncontradoParaProcesar && contenedoresDePerfil.length > 0) {
            intentosScrollSinExito++;
            console.log(`[Info] No hay perfiles nuevos. Intento de scroll ${intentosScrollSinExito}/${MAX_INTENTOS_SCROLL}.`);
            if (intentosScrollSinExito >= MAX_INTENTOS_SCROLL) {
                detenerProceso("Proceso completado: Se ha llegado al final de la lista.");
            } else {
                window.scrollTo(0, document.body.scrollHeight);
            }
        }
    }

    async function buclePrincipal() {
        while (procesoActivo) {
            await procesarUnPerfil();
            await esperar(INTERVALO_ENTRE_ACCIONES);
        }
    }

    // --- INICIO Y CREACIÓN DE INTERFAZ ---
    function inicializar() {
        panelInfo = document.createElement('div');
        panelInfo.style.cssText = 'position: fixed; top: 100px; right: 20px; z-index: 9998; background: rgba(255, 255, 255, 0.9); padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-family: Arial, sans-serif;';

        exitosDisplay = document.createElement('div');
        exitosDisplay.style.cssText = 'color: green; font-weight: bold;';

        fallosDisplay = document.createElement('div');
        fallosDisplay.style.cssText = 'color: red; font-weight: bold; margin-top: 5px;';

        panelInfo.appendChild(exitosDisplay);
        panelInfo.appendChild(fallosDisplay);
        document.body.appendChild(panelInfo);

        controlButton = document.createElement('button');
        controlButton.textContent = 'Iniciar Proceso';
        controlButton.style.cssText = 'position: fixed; top: 160px; right: 20px; z-index: 9999; padding: 10px 20px; background-color: #4267B2; color: white; border: none; border-radius: 5px; cursor: pointer;';
        document.body.appendChild(controlButton);

        actualizarUI();

        controlButton.addEventListener('click', () => {
            if (procesoActivo) {
                procesoActivo = false;
                controlButton.textContent = 'Iniciar Proceso';
                controlButton.style.backgroundColor = '#4267B2';
                console.log("[Control] Proceso detenido por el usuario. Finalizará después del ciclo actual.");
            } else {
                procesoActivo = true;
                controlButton.textContent = 'Detener Proceso';
                controlButton.style.backgroundColor = '#E0245E';
                console.log(`[Control] Proceso iniciado.`);
                buclePrincipal();
            }
        });
    }

    window.addEventListener('load', inicializar);

})();

Save the Script: Click "File" > "Save" and close the window.

Run the Script: Open Facebook, replace "youruser" with your username in the following link: https://www.facebook.com/youruser/following. This will take you to the "Following" page.

Start the Process: Click the "Iniciar Proceso" (Start Process) button on the top right corner, and the script will start unfollowing contacts one by one, displaying a counter for successful and failed unfollows.

Limitations:

Doesn't unfollow: Favorited contacts Groups or pages Only unfollows contacts

Manual Intervention Required: When the script encounters a page or group, you'll need to manually close the opened window to prevent the script from crashing.

To Avoid Bans: I recommend stopping the script every 400-500 contacts.

Hope this helps!

No need for extension.
https://github.com/matsyui/Facebook-Scripts/blob/main/auto-unfollow.md
image

@matsyui

matsyui commented Oct 31, 2025

Copy link
Copy Markdown

@ixus36900 i have also added support for Unlike

@Makharaa

Makharaa commented Nov 5, 2025

Copy link
Copy Markdown

@matsyui it does not work
Untitled

@matsyui

matsyui commented Nov 5, 2025

Copy link
Copy Markdown

@matsyui it does not work Untitled

For processOneProfile try to update the div.x78zum5.x1q0g3np.x1a02dak.x1qughib > div with your own selector.

test

@Makharaa

Makharaa commented Nov 5, 2025

Copy link
Copy Markdown

@matsyui It works on pages but doesn't unfollow persons. It gives me the error unfollow dialog not found.

@matsyui

matsyui commented Nov 6, 2025

Copy link
Copy Markdown

@matsyui It works on pages but doesn't unfollow persons. It gives me the error unfollow dialog not found.

You have to update this div.x78zum5.x1q0g3np.x1a02dak.x1qughib > div to your own elements

Step 1. right click name then click inspect element
image

Step 2. Find your selector
image

@daokethinh-tech

Copy link
Copy Markdown

image I am getting this error how to solve it?

@matsyui

matsyui commented Nov 6, 2025

Copy link
Copy Markdown

image I am getting this error how to solve it?

  1. Is your internet good? try increasing HOVER_WAIT_TIMEOUT
  2. Is your selector setup? Read the one above. should be like div.XXXXX.XXXXX.XXXX.XXXXX > div

@daokethinh-tech

Copy link
Copy Markdown

ảnh Tôi gặp lỗi này làm thế nào để giải quyết nó?

  1. Internet của bạn có tốt không? Thử tăng HOVER_WAIT_TIMEOUT
  2. Bộ chọn của bạn đã được thiết lập chưa? Đọc một ở trên. nên giống như div.XXXXX.XXXXX.XXXX.XXXXX > div

My internet is 100mb/s very good, has set the filter on Tampermonkey. Can you support me with Teamview or Ultraview? Thank you very much!
image

@matsyui

matsyui commented Nov 6, 2025

Copy link
Copy Markdown

ảnh Tôi gặp lỗi này làm thế nào để giải quyết nó?

  1. Internet của bạn có tốt không? Thử tăng HOVER_WAIT_TIMEOUT
  2. Bộ chọn của bạn đã được thiết lập chưa? Đọc một ở trên. nên giống như div.XXXXX.XXXXX.XXXX.XXXXX > div

My internet is 100mb/s very good, has set the filter on Tampermonkey. Can you support me with Teamview or Ultraview? Thank you very much! image

Do the step 2, after that paste the script in the console.

I dont do remote view

@jcarroll

jcarroll commented Jan 12, 2026

Copy link
Copy Markdown

image I am getting this error how to solve it?

@daokethinh-tech, Are you still looking for a solution? Looks like you're trying to use maysyui's excellent auto-unfriend script; is that correct?

@matsyui

matsyui commented Jan 12, 2026

Copy link
Copy Markdown

image I am getting this error how to solve it?

@daokethinh-tech, Are you still looking for a solution? Looks like you're trying to use maysyui's excellent auto-unfriend script; is that correct?

If this script and my script doesn't work...

Try this UI version (browser extension)

https://chromewebstore.google.com/detail/loc/eojdckfcadamkapabechhbnkleligand
https://loc.dev/

@cystec

cystec commented Apr 3, 2026

Copy link
Copy Markdown

**In 2026:

This will work on** https://www.facebook.com/pages/?category=liked&ref=bookmarks

(async () => {
  const sleep = (ms) => new Promise(r => setTimeout(r, ms));

  let stop = false;
  window.stopFbUnfollow = () => {
    stop = true;
    console.log("Stopping after current action...");
  };

  async function autoScroll() {
    let lastHeight = 0;
    let stableRounds = 0;

    while (!stop && stableRounds < 5) {
      window.scrollTo(0, document.body.scrollHeight);
      await sleep(1500);

      const newHeight = document.body.scrollHeight;
      if (newHeight === lastHeight) {
        stableRounds++;
      } else {
        stableRounds = 0;
        lastHeight = newHeight;
      }
    }
  }

  async function clickAll(selector, label) {
    while (!stop) {
      const buttons = [...document.querySelectorAll(selector)]
        .filter(el => el.offsetParent !== null);

      if (!buttons.length) {
        console.log(`No more ${label} buttons found.`);
        break;
      }

      console.log(`Found ${buttons.length} ${label} button(s).`);

      for (const btn of buttons) {
        if (stop) break;

        try {
          btn.click();
          console.log(`Clicked ${label}`);
        } catch (e) {
          console.log(`Failed clicking ${label}`, e);
        }

        await sleep(900);
      }

      await sleep(1200);
    }
  }

  console.log("Step 1: loading more pages...");
  await autoScroll();

  console.log("Step 2: unfollowing pages...");
  await clickAll('[aria-label="Following"]', 'Following');

  console.log("Step 3: unliking pages...");
  await clickAll('[aria-label="Liked"]', 'Liked');

  console.log("Done. Run stopFbUnfollow() to stop early next time.");
})();

@BayLak-Egypt

Copy link
Copy Markdown
  • FACEBOOK Unfollow Script - Specialized Version
  • Developed by: BayLak
  • Description: Automated script to handle Facebook unfollowing process via DOM manipulation.
    Usage: Run this in the browser console on the 'Following' page.
    IN 2026/5/9
    https://www.facebook.com/YourUserName/following and run the script.

console.log("%c [!] Script Started... Developed by BayLak.", "color: #00FF00; font-weight: bold;");

let intervalId = setInterval(function () {
    // Select all "More options" buttons dynamically
    let moreButtons = document.querySelectorAll('div[role="button"][aria-label*="More options"]');
    
    if (moreButtons.length > 0) {
        let currentBtn = moreButtons[0];
        currentBtn.click();
        setTimeout(() => {
            // 2. Identify the Unfollow option by role and text content
            let menuItems = document.querySelectorAll('div[role="menuitem"]');
            let unfollowBtn = Array.from(menuItems).find(item => 
                item.innerText.includes('Unfollow') || item.innerText.includes('إلغاء المتابعة')
            );

            if (unfollowBtn) {
                unfollowBtn.click();
                console.log("%c [+] Target Unfollowed.", "color: #00FF00");
            }

            let container = currentBtn.closest('div.x1gefphp');
            if (container) {
                container.remove();
            }
            window.scrollBy(0, 150);
        }, 700);

    } else {
        // Scroll down to fetch and render more items
        window.scrollBy(0, 500);
        console.log("Scanning for more targets...");
    }
}, 1800); 

@BayLak-Egypt

Copy link
Copy Markdown
  • Facebook Advanced Unfollow Bot - Stealth Version
  • Developed by: BayLak
  • Features: Auto-counting, Stealth scrolling, and Batch processing.

2026/5/9
https://www.facebook.com/YourUserName/following and run the script.


(function() {
    let unfollowCount = 0;
    const targetLimit = 100; // Set your limit here to avoid bans
    
    console.log("%c [!] BayLak Stealth Engine Activated.", "color: #FFA500; font-weight: bold;");

    async function startProcess() {
        // 1. Get all available follow buttons on the screen
        let moreButtons = document.querySelectorAll('div[role="button"][aria-label*="More options"]');
        console.log(`%c [i] Found ${moreButtons.length} accounts in current view.`, "color: #00FFFF");

        for (let btn of moreButtons) {
            if (unfollowCount >= targetLimit) {
                console.log("%c [!] Target limit reached. Stopping to stay safe.", "color: #FF0000");
                return;
            }

            // Click the more options
            btn.click();
            
            // Wait for DOM to update
            await new Promise(r => setTimeout(r, 600));

            let menuItems = document.querySelectorAll('div[role="menuitem"]');
            let unfollowBtn = Array.from(menuItems).find(item => 
                item.innerText.includes('Unfollow') || item.innerText.includes('إلغاء المتابعة')
            );

            if (unfollowBtn) {
                unfollowBtn.click();
                unfollowCount++;
                console.log(`%c [+] Unfollowed count: ${unfollowCount}`, "color: #00FF00");
            }

            // Clean up the DOM to free memory and avoid re-scanning
            btn.closest('div.x1gefphp')?.remove();

            // Dynamic delay to mimic human behavior (Randomized between 1-2 seconds)
            await new Promise(r => setTimeout(r, Math.random() * 1000 + 1000));
        }

        // 2. Scroll and repeat
        window.scrollBy({ top: 800, behavior: 'smooth' });
        console.log("%c [~] Scrolling for more...", "color: #BBBBBB");
        
        setTimeout(startProcess, 2000);
    }

    startProcess();
})();

@BayLak-Egypt

Copy link
Copy Markdown
  • FACEBOOK ATTACKER Unfollow + Live Analytics
  • Developed by: BayLak
  • Priority: Maximum Speed | Mode: Aggressive with Logging
    2026/5/9

https://www.facebook.com/YourUserName/following and run the script.


(function() {
    let totalUnfollowed = 0;
    let startTime = Date.now();

    console.clear();
    console.log(
        "%c" + 
        "██████╗  █████╗ ██╗   ██╗██╗      █████╗ ██╗  ██╗\n" +
        "██╔══██╗██╔══██╗╚██╗ ██╔╝██║     ██╔══██╗██║ ██╔╝\n" +
        "██████╔╝███████║ ╚████╔╝ ██║     ███████║█████╔╝ \n" +
        "██╔══██╗██╔══██║  ╚██╔╝  ██║     ██╔══██║██╔═██╗ \n" +
        "██████╔╝██║  ██║   ██║   ███████╗██║  ██║██║  ██╗\n" +
        "╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝\n" +
        "Developed by: Mohamed Hamada (BayLak Egypt)", 
        "color: #00FF00; font-weight: bold; font-family: monospace;"
    );

    console.log("%c [!] Hyper-Speed Engine Started. Monitoring Live...", "color: #FFFF00;");

    let hyperInterval = setInterval(() => {
        let buttons = document.querySelectorAll('div[role="button"][aria-label*="More options"]');
        
        if (buttons.length === 0) {
            window.scrollBy(0, 1000);
            return;
        }

        buttons.forEach((btn) => {
            btn.click();
            
            setTimeout(() => {
                let menuItems = document.querySelectorAll('div[role="menuitem"]');
                let found = false;
                
                menuItems.forEach((item) => {
                    if (item.innerText.includes('Unfollow') || item.innerText.includes('إلغاء المتابعة')) {
                        item.click();
                        found = true;
                    }
                });

                if (found) {
                    totalUnfollowed++;
                    let duration = ((Date.now() - startTime) / 1000).toFixed(1);
                    // Live Update in Console
                    console.log(
                        `%c [+] Unfollowed: ${totalUnfollowed} | Speed: ${(totalUnfollowed / duration).toFixed(2)} ops/sec | Time: ${duration}s`, 
                        "color: #00FF00; background: #000; border-left: 4px solid #00FF00; padding: 2px 10px;"
                    );
                }

                btn.closest('div.x1gefphp')?.remove();
            }, 5); // Near-zero delay for extreme speed
        });

        window.scrollBy(0, 600);

    }, 150); // Checks for new targets every 150ms

    // To stop the script and see final report
    window.stopBayLak = () => {
        clearInterval(hyperInterval);
        console.log(`%c [FINISH] Total Processed: ${totalUnfollowed} accounts.`, "color: #FF00FF; font-size: 16px; font-weight: bold;");
    };
})();

Screenshot from 2026-05-09 22-23-21

@reyhzer

reyhzer commented May 11, 2026

Copy link
Copy Markdown

anyone has working code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment