Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save braunglasrakete/837a136af79b43f1de8af41170849601 to your computer and use it in GitHub Desktop.
Save braunglasrakete/837a136af79b43f1de8af41170849601 to your computer and use it in GitHub Desktop.
Instagram Comment Activity Deleter: Automate the deletion of all your Instagram comments from the 'Your Activity' section. Perfect for quick digital clean-up. Also works for story replies. For Likes, see my other project.
/**
* Instagram Comment Auto-Deletion Script
* original by sbolel, updated to work with current page layout as of April 2025
* keep batch size low to reduce risk of Instagram throwing the SOMETHING WENT WRONG error
* it waits a little before selecting comments on reload to not throw it out of loop
* it's still not perfect, it occasionally throws SOMETHING WENT WRONG, but better semi-automated than not working at all
* if you're getting the message that there are no comments to show and you didn't comment on anything,
* go back to Home, and comment on something, then come back
*
* important: UI language must be set to English for the script to work
*
* WARNING: This function directly manipulates the DOM and depends on the current HTML
* structure of Instagram's website to work. If Instagram implements changes to the
* activity page layout, structure, or functionality, this script may break or cause
* unexpected behavior. Use at your own risk and always review code before running it.
*
* How to use:
* 1. Navigate to the Instagram comments page by going to:
* https://www.instagram.com/your_activity/interactions/comments
* 2. Open the developer console in your web browser:
* - Chrome/Firefox: Press Ctrl+Shift+J (Windows/Linux) or Cmd+Option+J (Mac)
* - Safari: Enable the Develop menu in Safari's Advanced preferences, then press Cmd+Option+C
* 3. Copy and paste this entire script into the console and press Enter to run it.
*
*/
;(async function () {
const DELETION_BATCH_SIZE = 12
const DELAY_BETWEEN_ACTIONS_MS = 1500
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 300
const DELAY_AFTER_SELECT_CLICK_MS = 8000 // NEW: Delay after clicking "Select"
const DELAY_AFTER_COMMENTS_VISIBLE_MS = 2000 // Wait before starting selection
const MAX_RETRIES = 60
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const waitForElement = async (selector, timeout = 30000) => {
const startTime = Date.now()
while (Date.now() - startTime < timeout) {
const element = document.querySelector(selector)
if (element) return element
await delay(100)
}
throw new Error(`Element with selector "${selector}" not found within ${timeout}ms`)
}
const clickElement = async (element) => {
if (!element) throw new Error('Element not found')
element.scrollIntoView({ behavior: 'smooth', block: 'center' })
element.click()
}
const waitForSelectButton = async () => {
for (let i = 0; i < MAX_RETRIES; i++) {
const buttonCount = document.querySelectorAll('[role="button"]')?.length
if (buttonCount > 1) return
await delay(1000)
}
throw new Error('Select button not found after maximum retries')
}
const deleteSelectedComments = async () => {
try {
const deleteButton = [...document.querySelectorAll('span')]
.find(el => ['Delete', 'Löschen'].includes(el.textContent.trim()))
if (!deleteButton) throw new Error('Delete button not found')
await clickElement(deleteButton)
await delay(DELAY_BETWEEN_ACTIONS_MS)
const confirmButton = await waitForElement('button[tabindex="0"]')
await clickElement(confirmButton)
} catch (error) {
console.error('Error during comment deletion:', error.message)
}
}
const scrollAndWaitForMoreComments = async (previousCount) => {
window.scrollTo(0, document.body.scrollHeight)
for (let i = 0; i < 10; i++) {
await delay(1000)
const currentCount = document.querySelectorAll('[aria-label="Toggle checkbox"]').length
if (currentCount > previousCount) return true
}
return false
}
const deleteActivity = async () => {
try {
while (true) {
const [, selectButton] = document.querySelectorAll('[role="button"]')
if (!selectButton) throw new Error('Select button not found')
await clickElement(selectButton)
await delay(DELAY_AFTER_SELECT_CLICK_MS) // NEW: Wait for comments to load
let checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
if (checkboxes.length === 0) {
const gotMore = await scrollAndWaitForMoreComments(0)
if (!gotMore) {
console.log('🚫 No more comments to delete.')
break
}
continue
}
await delay(DELAY_AFTER_COMMENTS_VISIBLE_MS) // Wait before starting selection
for (let i = 0; i < Math.min(DELETION_BATCH_SIZE, checkboxes.length); i++) {
await clickElement(checkboxes[i])
await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS)
}
await delay(DELAY_BETWEEN_ACTIONS_MS)
await deleteSelectedComments()
await delay(DELAY_BETWEEN_ACTIONS_MS)
await waitForSelectButton()
await delay(DELAY_BETWEEN_ACTIONS_MS)
}
} catch (error) {
console.error('Error in deleteActivity:', error.message)
}
}
// Start script
try {
await deleteActivity()
console.log('✅ All comments deleted or none left to delete.')
} catch (error) {
console.error('Fatal error:', error.message)
}
})()
@alessandroamella
Copy link

Great job! Very useful

@fugitiveghost
Copy link

I keep getting the issue of it opening my dms at the bottom of the screen, as well as saying all comments are deleted. my interface is in english as thats a common issue so I'm not sure why I'm getting it now. any help?

@Spiderdoom1313
Copy link

same issue as @fugitiveghost

@SmugFest
Copy link

works but i have the dm opeing issue

@ctrl-alt-w
Copy link

ctrl-alt-w commented Aug 29, 2025

this works:
@fugitiveghost, @Spiderdoom1313, @SmugFest I just tested it now:
;(async function () {
const DELETION_BATCH_SIZE = 20
const DELAY_BETWEEN_ACTIONS_MS = 3000
const DELAY_BETWEEN_CHECKBOX_CLICKS_MS = 100
const MAX_RETRIES = 100

const delay = ms => new Promise(res => setTimeout(res, ms))

async function slowScrollDown(totalDurationMs = 6000, steps = 6) {
    const totalHeight = document.body.scrollHeight
    const stepHeight = totalHeight / steps
    const stepDelay = totalDurationMs / steps
    for (let i = 0; i < steps; i++) {
        window.scrollBy(0, stepHeight)
        await delay(stepDelay)
    }
}

async function clickElement(el) {
    if (!el) throw new Error("Element not found")
    el.click()
}

async function getSelectButton() {
    const elems = [...document.querySelectorAll('[role="button"], span, div')]
    return elems.find(el => el.innerText.trim() === "Select") || null
}

async function getDeleteButton() {
    // Try multiple approaches to find the delete button
    
    // Method 1: Try the specific CSS selector you provided
    let deleteBtn = document.querySelector('.wbloks_50 > div:nth-child(1) > div:nth-child(4) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1)')
    if (deleteBtn) {
        console.log("Found delete button using CSS selector")
        return deleteBtn
    }

    // Method 2: Try to find by XPath (converted to querySelector)
    deleteBtn = document.evaluate('/html/body/div[1]/div/div/div[2]/div/div/div[1]/div[1]/div[1]/section/main/div/article/div/div[2]/div/div/div[1]/div/div/div/div/div/div[4]/div/div/div[2]/div/div/div[2]/div/div/div/div/div/div[1]/div/span', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue
    if (deleteBtn) {
        console.log("Found delete button using XPath")
        return deleteBtn
    }

    // Method 3: Look for elements containing "Delete" text (original method)
    const elems = [...document.querySelectorAll("span, div, button")]
    deleteBtn = elems.find(el => el.innerText && el.innerText.trim().toLowerCase().includes("delete"))
    if (deleteBtn) {
        console.log("Found delete button using text search")
        return deleteBtn
    }

    // Method 4: Look for clickable elements in the general area
    const clickableElems = [...document.querySelectorAll('[role="button"], button, .wbloks_50 span, .wbloks_50 div[role="button"]')]
    for (const elem of clickableElems) {
        if (elem.innerText && (elem.innerText.toLowerCase().includes('delete') || elem.getAttribute('aria-label')?.toLowerCase().includes('delete'))) {
            console.log("Found delete button using broader search")
            return elem
        }
    }

    console.log("Delete button not found with any method")
    return null
}

async function getConfirmButton() {
    // Try the specific selector you provided
    let confirmBtn = document.querySelector('button._a9--:nth-child(1)')
    if (confirmBtn) {
        console.log("Found confirm button using specific selector")
        return confirmBtn
    }

    // Fallback methods
    confirmBtn = document.querySelector('button[tabindex="0"]')
    if (confirmBtn) {
        console.log("Found confirm button using tabindex")
        return confirmBtn
    }

    // Look for buttons with confirm-related text
    const buttons = [...document.querySelectorAll('button')]
    confirmBtn = buttons.find(btn => {
        const text = btn.innerText?.toLowerCase() || ''
        return text.includes('delete') || text.includes('confirm') || text.includes('yes')
    })
    if (confirmBtn) {
        console.log("Found confirm button using text search")
        return confirmBtn
    }

    console.log("Confirm button not found")
    return null
}

async function handleWrongMessage() {
    const msgs = document.querySelectorAll("div, span, p")
    for (const msg of msgs) {
        if (msg.textContent.toLowerCase().includes("wrong")) {
            const buttons = document.querySelectorAll("button")
            for (const btn of buttons) {
                if (/^(ok)$/i.test(btn.textContent.trim())) {
                    await clickElement(btn)
                    await delay(500)
                    window.scrollTo(0, 0)
                    break
                }
            }
            break
        }
    }
}

async function waitForSelectButton() {
    for (let i = 0; i < MAX_RETRIES; i++) {
        const selectBtn = await getSelectButton()
        if (selectBtn) return selectBtn
        await delay(1000)
    }
    throw new Error("Select button not found after retries")
}

async function deleteSelectedComments() {
    try {
        console.log("Looking for delete button...")
        const deleteButton = await getDeleteButton()
        if (!deleteButton) throw new Error("Delete button not found")
        
        console.log("Clicking delete button...")
        await clickElement(deleteButton)
        await delay(DELAY_BETWEEN_ACTIONS_MS)

        console.log("Looking for confirmation button...")
        const confirmButton = await getConfirmButton()
        if (confirmButton) {
            console.log("Clicking confirm button...")
            await clickElement(confirmButton)
        } else {
            console.log("Warning: Confirmation button not found")
        }

        window.scrollTo(0, 0)
        await handleWrongMessage()
    } catch (err) {
        console.error("Error during comment deletion:", err.message)
    }
}

async function deleteActivity() {
    while (true) {
        const selectButton = await getSelectButton()
        if (!selectButton) throw new Error("Select button not found")

        await clickElement(selectButton)
        await delay(DELAY_BETWEEN_ACTIONS_MS)

        let checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
        let retries = 0

        while (checkboxes.length < DELETION_BATCH_SIZE && retries < 10) {
            await slowScrollDown(2000, 4)
            await delay(2000)
            checkboxes = document.querySelectorAll('[aria-label="Toggle checkbox"]')
            retries++
        }

        if (checkboxes.length === 0) {
            console.log("✅ No more comments to delete")
            return
        }

        for (let i = 0; i < Math.min(DELETION_BATCH_SIZE, checkboxes.length); i++) {
            await clickElement(checkboxes[i])
            await delay(DELAY_BETWEEN_CHECKBOX_CLICKS_MS)
        }

        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await deleteSelectedComments()
        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await waitForSelectButton()
        await delay(DELAY_BETWEEN_ACTIONS_MS)
        await handleWrongMessage()
    }
}

try {
    await deleteActivity()
    console.log("🎉 Deletion finished")
} catch (err) {
    console.error("Fatal error:", err.message)
}

})()

@zackdarver-ctrl
Copy link

?

@zackdarver-ctrl
Copy link

?

@zackdarver-ctrl
Copy link

Ok

@zackdarver-ctrl
Copy link

What do I need to do

@braunglasrakete
Copy link
Author

Just FYI, I updated this to serve my purpose back then and I will not maintain or update this any further. It is here for reference, for people to fork and update if need be. Thanks for understanding.

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