Unfollow all pages in Facebook with an automatic script using Edge browser

1 – Go to https://www.facebook.com/pages/?category=liked&ref=bookmarks and scroll to the bottom

2 – Press Ctrl + Shift + I to open the console

3 – Paste this script and hit enter:
(async () => {
// Configuration
const delayBetweenActions = 5000; // 5s between unfollows
const maxActionsBeforeShortPause = 5; // Pause after 5 unfollows
const shortPauseDuration = 30000; // 30s pause
const maxRuntimeBeforeLongPause = 300000; // 5min before long pause
const longPauseDuration = 300000; // 5min pause

// Helper functions
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const cleanPageName = (name) => {
    return name.replace(/(\bFollow\b|\bLike\b|\bDigital creator\b|\bPage\b|\bCommunity\b|\bPublic figure\b|\bAll Pages\b|\bor\b|\b\(\d+\)\b|\s*$)/gi, '').trim();
};

console.log('Script started. Unfollowing ALL Liked Pages...');

// Main loop
let actionCount = 0; // Unfollows in current batch
let totalPagesProcessed = 0; // Total buttons processed
let continueProcessing = true;
let startTime = Date.now(); // Track runtime

while (continueProcessing) {
    // Check for 5-minute pause
    const currentTime = Date.now();
    if (currentTime - startTime >= maxRuntimeBeforeLongPause) {
        console.log(`Pausing for 5 minutes after running for 5 minutes...`);
        await sleep(longPauseDuration);
        startTime = Date.now();
        console.log('Resuming script...');
    }

    // Find "Following" buttons within page list
    const buttons = Array.from(document.querySelectorAll('div[class*="x1a02dak"] div[aria-label="Following"]'))
        .filter(button => {
            // Ensure button is in a page entry with a name
            const container = button.closest('div[class*="x1a02dak"], div[class*="x1swvt13"]');
            return container && container.querySelector('span[class*="x1lliihq"], a[class*="x1lliihq"], h3, h4');
        });
    console.log(`Found ${buttons.length} valid Following buttons on this iteration.`);

    if (buttons.length === 0) {
        console.log('No valid Following buttons found. Possible reasons:');
        console.log('- All pages unfollowed.');
        console.log('- Pages not loaded (try scrolling to the bottom).');
        console.log('- UI changed (check aria-label or container classes).');
        console.log('- Wrong page (ensure you’re at /pages/?category=liked).');
        break;
    }

    // Reset processed IDs per iteration to avoid false duplicates
    let processedButtonIds = new Set();

    for (let i = 0; i < buttons.length; i++) {
        const button = buttons[i];
        totalPagesProcessed++;
        console.log(`Processing button ${totalPagesProcessed}`);

        // Find page container
        const pageContainer = button.closest('div[class*="x1a02dak"], div[class*="x1swvt13"]');
        if (!pageContainer) {
            console.log('Skipping: No page container found.');
            console.log('Button HTML:', button.outerHTML.slice(0, 300));
            continue;
        }

        // Find page name
        let pageNameElement = pageContainer.querySelector('span[class*="x1lliihq"], a[class*="x1lliihq"], h3, h4, div[class*="xt7dq6l"]');
        let pageName = pageNameElement ? pageNameElement.textContent.trim() : 'Unknown';
        pageName = cleanPageName(pageName);

        if (!pageName || pageName.toLowerCase() === 'following' || pageName.toLowerCase() === 'like' || pageName === 'Unknown') {
            console.log('Skipping: No valid page name found.');
            console.log('Container HTML:', pageContainer.outerHTML.slice(0, 300));
            continue;
        }

        // Create unique button ID
        const buttonId = `button-${totalPagesProcessed}-${pageName}`;
        if (processedButtonIds.has(buttonId)) {
            console.log(`Skipping: Already processed button for "${pageName}".`);
            continue;
        }

        console.log(`Page name: ${pageName}`);
        console.log(`Attempting to unfollow: ${pageName}`);

        try {
            // Click Following button once
            button.click();
            console.log(`Clicked Following button for: ${pageName}`);
            actionCount++;
            processedButtonIds.add(buttonId);

            // Handle prompts (e.g., Confirm)
            const updateButton = document.querySelector('div[aria-label="Update"], div[aria-label="Confirm"]');
            if (updateButton) {
                updateButton.click();
                console.log('Clicked "Update/Confirm" button.');
            }

            // Short pause handling
            if (actionCount >= maxActionsBeforeShortPause) {
                console.log(`Pausing for 30 seconds after ${actionCount} unfollows...`);
                await sleep(shortPauseDuration);
                actionCount = 0;
            } else {
                await sleep(delayBetweenActions);
            }
        } catch (error) {
            console.error(`Error clicking Following button for "${pageName}":`, error);
            button.click(); // Attempt to close any open state
        }
    }

    // Scroll to load more pages
    console.log('Scrolling to load more pages...');
    window.scrollTo(0, document.body.scrollHeight);
    await sleep(15000);

    // Check if more pages loaded
    const newButtons = document.querySelectorAll('div[class*="x1a02dak"] div[aria-label="Following"]');
    console.log(`After scrolling, found ${newButtons.length} Following buttons.`);
    if (newButtons.length === buttons.length) {
        console.log('No new pages loaded. Stopping.');
        continueProcessing = false;
    }
}

console.log(`Script completed. Processed ${totalPagesProcessed} pages.`);
console.log(`Unfollowed ${actionCount} pages.`);

})();

I had to do this because a hacker followed thousands of pages under my profile without my consent. So, I am unfollowing everything so I can eventually follow only the ones I like.