pacmax beta

Userscripts Pac by max

TikTok Bulk Unsaver

Unsave TikTok Posts!

Quickly unsave posts from your TikTok account, with a few options.

The code

This is the script you get from the button above. Read it before you install: a userscript runs inside the pages it matches.

  • Runs on https://www.tiktok.com/*
  • Special access None asked for.
tiktok-bulk-unsaver.user.js552 lines
// ==UserScript==
// @name         TikTok Bulk Unsave
// @namespace    max.tiktok.bulk-unsave
// @version      1.2.0
// @description  Bulk remove saved posts (Favorites) on tiktok.com with a small control panel
// @match        https://www.tiktok.com/*
// @run-at       document-start
// @noframes
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  // ---------- Settings (editable in the panel, saved between visits) ----------
  const DEFAULTS = { minDelay: 3, maxDelay: 6, maxItems: 0, startAfter: 0 }; // seconds, seconds, 0 = no cap, posts to keep at the top
  const STORE_KEY = 'tbu-settings';
  const cfg = Object.assign({}, DEFAULTS, loadSettings());

  // ---------- Selectors. TikTok renames these often, so each has fallbacks ----------
  const SEL = {
    profileLink: ['[data-e2e="nav-profile"]', 'a[data-e2e="profile-icon"]'],
    favTab: ['[data-e2e="favorites-tab"]', '[data-e2e="favorite-tab"]', '[role="tab"][class*="Favorite"]'],
    gridItem: [
      '[data-e2e="favorites-item"] a[href]',
      '[data-e2e="favorites-item"]',
      '[data-e2e="favorites-item-list"] a[href*="/video/"]',
      '[data-e2e="favorites-item-list"] a[href*="/photo/"]',
    ],
    // Tried in order. The first group that matches anything is the one used.
    favBtn: [
      '[data-e2e="favorite-icon"]',
      '[data-e2e="browse-favorite-icon"]',
      '[data-e2e="undefined-icon"]',
      'button[aria-label*="favorite" i], button[aria-label*="favourite" i]',
    ],
    favCount: '[data-e2e="favorite-count"], [data-e2e="browse-favorite-count"], [data-e2e="undefined-count"]',
    next: ['[data-e2e="arrow-right"]', 'button[aria-label*="next video" i]', 'button[aria-label="Next"]'],
  };

  // ---------- State ----------
  let running = false;
  let removed = 0;
  let confirmed = 0; // unsaves TikTok's server answered OK to
  let skipped = 0;
  let kept = 0; // posts passed over at the start because of "Start after"
  let lastReject = '';

  // ---------- Watch TikTok's own save/unsave responses ----------
  // The button flips in the UI even when the server refuses the request, so the UI can't be trusted.
  // This only reads responses to requests TikTok itself makes. It never sends anything.
  const COLLECT_RE = /\/api\/item\/collect\//;
  let lastCollect = null; // { ok: true | false | null, detail }

  function onCollectResponse(http, text) {
    let code = null;
    let msg = '';
    try {
      const j = JSON.parse(text);
      code = j.status_code ?? j.statusCode ?? null;
      msg = j.status_msg || j.statusMsg || '';
    } catch { /* not JSON */ }
    const body = (text || '').trim();
    let ok = null; // unknown
    if (http < 200 || http >= 300) ok = false;
    else if (code === 0 || body === '') ok = true;
    else if (code !== null) ok = false;
    const detail = `HTTP ${http}` + (code !== null ? `, code ${code}` : '') + (msg ? `, "${msg}"` : '');
    lastCollect = { ok, detail };
    console.log('[Bulk Unsave] server response:', detail, ok === false ? '(REJECTED)' : '', body.slice(0, 300));
  }

  (function hookNetwork() {
    try {
      const xhrOpen = XMLHttpRequest.prototype.open;
      const xhrSend = XMLHttpRequest.prototype.send;
      XMLHttpRequest.prototype.open = function (method, url) {
        this.__tbuUrl = String(url);
        return xhrOpen.apply(this, arguments);
      };
      XMLHttpRequest.prototype.send = function () {
        if (COLLECT_RE.test(this.__tbuUrl || '')) {
          this.addEventListener('loadend', () => {
            let text = '';
            try {
              text = this.responseType === '' || this.responseType === 'text'
                ? this.responseText
                : JSON.stringify(this.response);
            } catch { /* ignore */ }
            onCollectResponse(this.status, text || '');
          });
        }
        return xhrSend.apply(this, arguments);
      };

      const origFetch = window.fetch;
      if (typeof origFetch === 'function') {
        window.fetch = function (...args) {
          const p = origFetch.apply(this, args);
          try {
            const url = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].url) || String(args[0]);
            if (COLLECT_RE.test(url)) {
              p.then((res) => res.clone().text().then((t) => onCollectResponse(res.status, t))).catch(() => {});
            }
          } catch { /* ignore */ }
          return p;
        };
      }
    } catch (err) {
      console.warn('[Bulk Unsave] could not hook network, counts will be unconfirmed', err);
    }
  })();

  async function waitForCollect(timeout = 2500) {
    const end = Date.now() + timeout;
    while (Date.now() < end) {
      if (lastCollect) return lastCollect;
      await sleep(100);
    }
    return null;
  }
  const seenIds = new Set();
  const seenEls = new WeakSet();

  // ---------- Helpers ----------
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const randDelay = () => {
    const lo = Math.max(0.3, Number(cfg.minDelay) || DEFAULTS.minDelay);
    const hi = Math.max(lo, Number(cfg.maxDelay) || DEFAULTS.maxDelay);
    return (lo + Math.random() * (hi - lo)) * 1000;
  };

  function loadSettings() {
    try { return JSON.parse(localStorage.getItem(STORE_KEY)) || {}; } catch { return {}; }
  }
  function saveSettings() {
    try { localStorage.setItem(STORE_KEY, JSON.stringify(cfg)); } catch { /* ignore */ }
  }

  async function waitFor(fn, timeout = 8000, step = 200) {
    const end = Date.now() + timeout;
    while (Date.now() < end) {
      if (!running) return null;
      const v = fn();
      if (v) return v;
      await sleep(step);
    }
    return null;
  }

  function hasSize(el) {
    const r = el.getBoundingClientRect();
    return r.width > 0 && r.height > 0;
  }
  function inViewport(el) {
    const r = el.getBoundingClientRect();
    return r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth;
  }
  function firstVisible(selectors) {
    for (const s of selectors) {
      for (const el of document.querySelectorAll(s)) if (inViewport(el)) return el;
    }
    return null;
  }
  const clickable = (el) => el.closest('button, [role="button"]') || el;

  // All favorite buttons currently in the DOM (feed view can have several loaded).
  function allFavBtns() {
    for (const s of SEL.favBtn) {
      const out = [];
      for (const el of document.querySelectorAll(s)) {
        if (el.closest('#tbu-panel') || el.closest('[role="tab"]')) continue;
        const btn = clickable(el);
        if (hasSize(btn) && !out.includes(btn)) out.push(btn);
      }
      if (out.length) return out;
    }
    return [];
  }

  // The favorite button of whichever post is nearest the middle of the screen.
  function centeredFavBtn() {
    const mid = innerHeight / 2;
    let best = null;
    let bestDist = Infinity;
    for (const btn of allFavBtns()) {
      if (!inViewport(btn)) continue;
      const r = btn.getBoundingClientRect();
      const d = Math.abs(r.top + r.height / 2 - mid);
      if (d < bestDist) { best = btn; bestDist = d; }
    }
    return best;
  }

  function currentId() {
    const m = location.pathname.match(/\/(?:video|photo)\/(\d+)/);
    return m ? m[1] : null;
  }

  // A post is "new" if we have not touched this button element, or the URL shows an ID we have not handled.
  function isNew(btn, id) {
    return !seenEls.has(btn) || (id !== null && !seenIds.has(id));
  }
  function mark(btn, id) {
    if (btn) seenEls.add(btn);
    if (id) seenIds.add(id);
  }

  function isYellow(color) {
    const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(color || '');
    if (!m) return false;
    const [r, g, b] = [+m[1], +m[2], +m[3]];
    return r > 200 && g > 150 && b < 110; // TikTok's saved color is roughly rgb(250, 206, 21)
  }

  // true = saved, false = not saved, null = can't tell.
  function favState(btn) {
    const pressed = btn.getAttribute('aria-pressed') ??
      btn.querySelector('[aria-pressed]')?.getAttribute('aria-pressed');
    if (pressed === 'true') return true;
    if (pressed === 'false') return false;
    for (const el of btn.querySelectorAll('svg, svg *')) {
      const cs = getComputedStyle(el);
      if (isYellow(cs.fill) || isYellow(cs.color)) return true;
    }
    return null;
  }

  // Only usable when the count is a plain number (not "12.3K").
  function readCount(btn) {
    const el = btn.querySelector(SEL.favCount) || btn.parentElement?.querySelector(SEL.favCount);
    const t = el?.textContent.trim();
    return t && /^\d+$/.test(t) ? Number(t) : null;
  }

  function scrollParent(el) {
    for (let p = el.parentElement; p; p = p.parentElement) {
      const oy = getComputedStyle(p).overflowY;
      if ((oy === 'auto' || oy === 'scroll') && p.scrollHeight > p.clientHeight + 10) return p;
    }
    return document.scrollingElement;
  }

  function pressKey(key, keyCode) {
    for (const type of ['keydown', 'keyup']) {
      document.body.dispatchEvent(new KeyboardEvent(type, { key, code: key, keyCode, which: keyCode, bubbles: true }));
    }
  }

  // ---------- Getting to the first saved post ----------
  function findFavTab() {
    const el = firstVisible(SEL.favTab);
    if (el) return el;
    for (const t of document.querySelectorAll('[role="tab"]')) {
      if (/^favou?rites$/i.test(t.textContent.trim()) && inViewport(t)) return t;
    }
    return null;
  }

  async function ensureViewer() {
    if (centeredFavBtn() && currentId()) {
      return confirm('A post is already open.\n\nOnly continue if you opened it from your Favorites tab, otherwise this could start saving posts instead of unsaving them.\n\nContinue?');
    }

    let tab = findFavTab();
    if (!tab) {
      const profile = firstVisible(SEL.profileLink);
      if (profile) {
        setStatus('Opening your profile...');
        clickable(profile).click();
        tab = await waitFor(findFavTab, 10000);
      }
    }
    if (!tab) {
      setStatus('Go to your profile page, then hit Start again.');
      return false;
    }

    setStatus('Opening Favorites...');
    tab.click();
    await sleep(1500);
    const item = await waitFor(() => firstVisible(SEL.gridItem), 10000);
    if (!item) {
      setStatus('No saved posts found. If there are some, open the first one yourself and hit Start.');
      return false;
    }

    item.click();
    const btn = await waitFor(centeredFavBtn, 10000);
    if (!btn) {
      setStatus("Opened a post but couldn't find the Favorite button. TikTok likely changed its markup.");
      return false;
    }
    await sleep(800);
    return true;
  }

  // ---------- Unsave one post. Returns 'removed', 'skipped', or 'failed' ----------
  async function processOne(btn, id) {
    const before = favState(btn);
    const countBefore = readCount(btn);

    if (before === false) {
      mark(btn, id);
      return 'skipped';
    }

    lastCollect = null;
    btn.click();
    await sleep(800);
    const resp = await waitForCollect();

    const fresh = centeredFavBtn() || btn;
    const after = favState(fresh);
    const countAfter = readCount(fresh);
    const countUp = countBefore !== null && countAfter !== null && countAfter > countBefore;

    let result = 'removed';
    if (before !== true && (after === true || countUp)) {
      // It wasn't saved and we just saved it. Undo.
      fresh.click();
      await sleep(600);
      result = 'skipped';
    } else if (before === true && after === true) {
      // Click didn't take. Usually rate limiting.
      result = 'failed';
    }

    // The UI can say "unsaved" while the server said no. The server wins.
    if (result === 'removed' && resp) {
      if (resp.ok === false) {
        result = 'failed';
        lastReject = resp.detail;
      } else if (resp.ok === true) {
        confirmed++;
      }
    }

    mark(btn, id);
    mark(fresh, id);
    return result;
  }

  // ---------- Move to the next post. Returns true if a new post is on screen ----------
  async function advance(prevBtn) {
    const prevTop = prevBtn.getBoundingClientRect().top;
    const strategies = [
      // Feed-style viewer: scroll the next loaded post into view.
      () => {
        const next = allFavBtns()
          .filter((b) => !seenEls.has(b) && b.getBoundingClientRect().top > prevTop + 50)
          .sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top)[0];
        if (!next) return false;
        next.scrollIntoView({ block: 'center', behavior: 'smooth' });
        return true;
      },
      // Older modal viewer: next arrow.
      () => {
        const arrow = firstVisible(SEL.next);
        if (!arrow || arrow.disabled) return false;
        clickable(arrow).click();
        return true;
      },
      () => { pressKey('ArrowDown', 40); return true; },
      () => {
        const sc = scrollParent(prevBtn);
        if (!sc) return false;
        sc.scrollBy({ top: sc.clientHeight || innerHeight, behavior: 'smooth' });
        return true;
      },
    ];

    for (const tryMove of strategies) {
      if (!running) return false;
      if (!tryMove()) continue;
      const ok = await waitFor(() => {
        const b = centeredFavBtn();
        return b && isNew(b, currentId());
      }, 3000);
      if (ok) {
        await sleep(400); // let it settle
        return true;
      }
    }
    return false;
  }

  // ---------- Main loop ----------
  async function run() {
    running = true;
    removed = 0;
    confirmed = 0;
    skipped = 0;
    kept = 0;
    lastReject = '';
    seenIds.clear();
    render();

    try {
      if (!(await ensureViewer())) return;

      let failStreak = 0;
      while (running) {
        const cap = Number(cfg.maxItems) || 0;
        if (cap > 0 && removed >= cap) {
          setStatus(`Hit your cap of ${cap}.`);
          break;
        }

        const btn = await waitFor(centeredFavBtn, 8000);
        if (!running) break;
        if (!btn) {
          setStatus('Lost the Favorite button. Stopping.');
          break;
        }

        const id = currentId();
        const keepCount = Math.floor(Number(cfg.startAfter) || 0);
        if (isNew(btn, id) && kept < keepCount) {
          // Leave this one saved and move on.
          mark(btn, id);
          kept++;
          render();
          setStatus(`Keeping the first ${keepCount}: passed ${kept}...`);
          await sleep(400);
          if (!running) break;
        } else if (isNew(btn, id)) {
          const result = await processOne(btn, id);
          if (result === 'removed') { removed++; failStreak = 0; }
          else if (result === 'skipped') { skipped++; failStreak = 0; }
          else { failStreak++; }
          render();

          if (failStreak >= 2) {
            setStatus(lastReject
              ? `TikTok is rejecting unsaves (${lastReject}). Nothing more will stick right now. Wait a few hours and run again with longer delays.`
              : 'TikTok is ignoring the clicks, probably rate limiting. Wait a few hours and run again.');
            break;
          }
          setStatus(removed >= 3 && confirmed === 0
            ? "Working, but I can't see TikTok's responses, so the count is unconfirmed."
            : 'Working...');
          await sleep(randDelay());
          if (!running) break;
        }

        if (!(await advance(btn))) {
          if (running) setStatus('No more posts to move to. Refresh Favorites and run again to catch any stragglers.');
          break;
        }
      }
    } catch (err) {
      console.error('[TikTok Bulk Unsave]', err);
      setStatus('Error: ' + err.message);
    } finally {
      running = false;
      render();
    }
  }

  // ---------- Panel ----------
  let panel, startBtn, countEl, statusEl;

  function setStatus(text) {
    if (statusEl) statusEl.textContent = text;
  }

  function render() {
    if (!panel) return;
    startBtn.textContent = running ? 'Stop' : 'Start';
    startBtn.style.background = running ? '#555' : '#fe2c55';
    countEl.textContent = `Unsaved: ${removed} (${confirmed} confirmed)` + (kept ? `  Kept: ${kept}` : '') + (skipped ? `  Skipped: ${skipped}` : '');
  }

  function numberField(label, key, step) {
    const wrap = document.createElement('label');
    wrap.style.cssText = 'display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:6px;';
    const span = document.createElement('span');
    span.textContent = label;
    const input = document.createElement('input');
    input.type = 'number';
    input.min = '0';
    input.step = step;
    input.value = cfg[key];
    input.style.cssText = 'width:64px;padding:3px 5px;border-radius:5px;border:1px solid #555;background:#222;color:#fff;font:inherit;';
    input.addEventListener('change', () => {
      const v = Number(input.value);
      cfg[key] = Number.isFinite(v) && v >= 0 ? v : DEFAULTS[key];
      input.value = cfg[key];
      saveSettings();
    });
    // Keep TikTok's keyboard shortcuts from firing while typing here.
    for (const type of ['keydown', 'keyup', 'keypress']) input.addEventListener(type, (e) => e.stopPropagation());
    wrap.append(span, input);
    return wrap;
  }

  function buildPanel() {
    panel = document.createElement('div');
    panel.id = 'tbu-panel';
    panel.style.cssText = [
      'position:fixed', 'right:16px', 'bottom:16px', 'z-index:2147483647', 'width:230px',
      'padding:12px', 'border-radius:10px', 'background:rgba(22,22,22,.95)', 'color:#fff',
      'font:13px/1.35 system-ui,-apple-system,Segoe UI,sans-serif', 'box-shadow:0 4px 18px rgba(0,0,0,.45)',
    ].join(';');

    const title = document.createElement('div');
    title.textContent = 'Bulk Unsave';
    title.style.cssText = 'font-weight:600;margin-bottom:8px;';

    startBtn = document.createElement('button');
    startBtn.type = 'button';
    startBtn.style.cssText = 'width:100%;padding:7px 0;border:0;border-radius:6px;color:#fff;font:inherit;font-weight:600;cursor:pointer;';
    startBtn.addEventListener('click', () => {
      if (running) {
        running = false;
        setStatus('Stopped.');
        render();
      } else {
        setStatus('Starting...');
        run();
      }
    });

    countEl = document.createElement('div');
    countEl.style.cssText = 'margin-top:8px;';

    statusEl = document.createElement('div');
    statusEl.style.cssText = 'margin-top:4px;color:#bbb;min-height:1.35em;';
    statusEl.textContent = 'Open your profile, then hit Start.';

    panel.append(
      title,
      startBtn,
      countEl,
      statusEl,
      numberField('Min delay (s)', 'minDelay', '0.5'),
      numberField('Max delay (s)', 'maxDelay', '0.5'),
      numberField('Start after (0 = top)', 'startAfter', '1'),
      numberField('Stop after (0 = all)', 'maxItems', '1'),
    );
    render();
  }

  function mountPanel() {
    if (!panel) buildPanel();
    if (!panel.isConnected && document.body) document.body.appendChild(panel);
  }

  mountPanel();
  setInterval(mountPanel, 2000); // TikTok is a SPA and sometimes rebuilds the page body
})();

SHA-256 dfd2e84f75b1e61ed83f6e49a2afc004e4994d4227edb648734e4cd5a232032e

Latest release