pacmax beta

Userscripts Pac by max

TikTok Follows

Sort and filter your TikTok following/followers lists (followers, follows back, verified, private) and export to CSV.

Tools for managing your follows on TikTok

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-follows.user.js609 lines
// ==UserScript==
// @name         TikTok Following Filter
// @namespace    max.tiktok.following.filter
// @version      1.1.0
// @description  Sort and filter your TikTok following/followers lists (followers, follows back, verified, private) and export to CSV.
// @match        https://www.tiktok.com/*
// @run-at       document-start
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  // ---------------------------------------------------------------------------
  // Data capture. Three layers, because userscript managers differ in how much
  // of the page they let a script see (iOS Safari sandboxes scripts):
  //   1. Hook fetch/XHR and read TikTok's own list responses.
  //   2. Watch the browser's resource log for list requests and re-read them.
  //   3. Read the open list straight off the screen, then pull each account's
  //      stats from its profile page.
  // Nothing is sent anywhere. Everything stays in this tab.
  // ---------------------------------------------------------------------------
  const LIST_URL = /\/api\/user\/list/;
  const SCENE_LABELS = { '21': 'Following', '67': 'Followers' };
  const buckets = new Map(); // label -> Map(lowercase username -> row)
  const debug = { hook: 0, replay: 0, dom: 0, profile: 0 };
  const handledUrls = new Set();
  const nativeFetch = typeof window.fetch === 'function' ? window.fetch.bind(window) : null;
  let order = 0;

  function getBucket(label) {
    if (!buckets.has(label)) buckets.set(label, new Map());
    return buckets.get(label);
  }

  function labelForUrl(url) {
    let scene = '';
    try { scene = new URL(url, location.origin).searchParams.get('scene') || ''; } catch (e) {}
    return SCENE_LABELS[scene] || (scene ? 'List (scene ' + scene + ')' : 'Following');
  }

  function blankRow(uniqueId) {
    return {
      order: order++, uniqueId: uniqueId, nickname: '', avatar: '', verified: false, isPrivate: false,
      relation: null, domMutual: null, hasStats: false, statsFailed: false,
      followers: 0, following: 0, likes: 0, videos: 0,
    };
  }

  function applyApi(row, u, s) {
    if (u.nickname) row.nickname = u.nickname;
    if (u.avatarThumb || u.avatarMedium) row.avatar = u.avatarThumb || u.avatarMedium;
    row.verified = !!u.verified;
    row.isPrivate = !!(u.privateAccount || u.secret);
    if (typeof u.relation === 'number') row.relation = u.relation;
    if (s && s.followerCount != null) {
      row.followers = Number(s.followerCount) || 0;
      row.following = Number(s.followingCount) || 0;
      row.likes = Number(s.heartCount || s.heart) || 0;
      row.videos = Number(s.videoCount) || 0;
      row.hasStats = true;
    }
  }

  function ingest(url, data, source) {
    const list = data && Array.isArray(data.userList) ? data.userList : null;
    if (!list || !list.length) return;
    const bucket = getBucket(labelForUrl(url));
    for (const item of list) {
      const u = (item && item.user) || {};
      if (!u.uniqueId) continue;
      const key = u.uniqueId.toLowerCase();
      if (!bucket.has(key)) bucket.set(key, blankRow(u.uniqueId));
      applyApi(bucket.get(key), u, (item && item.stats) || null);
    }
    debug[source]++;
    scheduleRender();
  }

  // Layer 1: hooks (only effective when the script runs in the page's own world)
  if (nativeFetch) {
    window.fetch = function (input) {
      const p = nativeFetch.apply(this, arguments);
      try {
        const reqUrl = typeof input === 'string' ? input : (input && input.url) || '';
        if (LIST_URL.test(reqUrl)) {
          p.then(function (res) {
            res.clone().json().then(function (d) {
              handledUrls.add(res.url || reqUrl);
              ingest(res.url || reqUrl, d, 'hook');
            }).catch(function () {});
          }).catch(function () {});
        }
      } catch (e) {}
      return p;
    };
  }

  const origOpen = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url) {
    try {
      const u = String(url);
      if (LIST_URL.test(u)) {
        this.addEventListener('load', function () {
          try {
            const d = this.responseType === 'json' ? this.response : JSON.parse(this.responseText);
            handledUrls.add(this.responseURL || u);
            ingest(u, d, 'hook');
          } catch (e) {}
        });
      }
    } catch (e) {}
    return origOpen.apply(this, arguments);
  };

  // Layer 2: the resource log is visible even from a sandboxed script. When a
  // list request shows up there that the hooks missed, read the same URL again.
  function replay(url) {
    if (handledUrls.has(url) || !nativeFetch) return;
    handledUrls.add(url);
    nativeFetch(url, { credentials: 'include' })
      .then(function (r) { return r.json(); })
      .then(function (d) { ingest(url, d, 'replay'); })
      .catch(function () {});
  }
  function onResources(entries) {
    entries.forEach(function (e) {
      if (!LIST_URL.test(e.name)) return;
      setTimeout(function () { replay(e.name); }, 1200); // give the hooks first shot
    });
  }
  try {
    new PerformanceObserver(function (l) { onResources(l.getEntries()); }).observe({ type: 'resource', buffered: true });
  } catch (e) {
    try { onResources(performance.getEntriesByType('resource')); } catch (e2) {}
  }

  // Layer 3a: read the open list off the screen.
  function findScroller() {
    let best = null;
    const nodes = document.querySelectorAll('[role="dialog"] *, [class*="Modal"] *, [class*="modal"] *');
    for (const n of nodes) {
      if (ui && ui.panel.contains(n)) continue;
      if (n.scrollHeight <= n.clientHeight + 20) continue;
      const oy = getComputedStyle(n).overflowY;
      if (oy !== 'auto' && oy !== 'scroll') continue;
      if (!n.querySelector('a[href*="/@"]')) continue;
      if (!best || n.scrollHeight > best.scrollHeight) best = n;
    }
    return best;
  }

  const TAB_RE = /^(Following|Followers|Friends|Suggested)\s*[\d.,KMB]*$/i;
  function brightness(node) {
    const m = getComputedStyle(node).color.match(/[\d.]+/g);
    if (!m || m.length < 3) return 0;
    return (Number(m[0]) + Number(m[1]) + Number(m[2])) * (m.length > 3 ? Number(m[3]) : 1);
  }
  // Which tab of TikTok's list is showing: the brightest tab label wins.
  function activeTab(scroller) {
    let root = scroller;
    for (let i = 0; i < 8 && root.parentElement; i++) {
      root = root.parentElement;
      const scores = {};
      let selected = null;
      root.querySelectorAll('*').forEach(function (n) {
        if (n.children.length > 2 || scroller.contains(n)) return;
        const m = (n.textContent || '').trim().match(TAB_RE);
        if (!m) return;
        const label = m[1].charAt(0).toUpperCase() + m[1].slice(1).toLowerCase();
        scores[label] = Math.max(scores[label] || 0, brightness(n));
        const tab = n.closest('[aria-selected="true"]');
        if (tab && root.contains(tab)) selected = label;
      });
      if (scores.Following != null && scores.Followers != null) {
        if (selected) return selected;
        return Object.keys(scores).sort(function (a, b) { return scores[b] - scores[a]; })[0];
      }
    }
    return 'Following';
  }

  function rowTexts(node) {
    if (typeof node.innerText === 'string') return node.innerText.split('\n').map(function (t) { return t.trim(); }).filter(Boolean);
    return Array.from(node.querySelectorAll('*')).filter(function (e) { return !e.children.length; })
      .map(function (e) { return (e.textContent || '').trim(); }).filter(Boolean);
  }

  function scrapeDom() {
    if (!ui) return;
    const scroller = findScroller();
    if (!scroller) return;
    const tab = activeTab(scroller);
    if (tab !== 'Following' && tab !== 'Followers') return;
    const bucket = getBucket(tab);
    let changed = false;
    scroller.querySelectorAll('a[href*="/@"]').forEach(function (a) {
      const part = (a.getAttribute('href') || '').split('/@')[1];
      if (!part) return;
      let uniqueId = part.split(/[/?#]/)[0];
      try { uniqueId = decodeURIComponent(uniqueId); } catch (e) {}
      if (!uniqueId) return;
      // Climb to the row: the smallest ancestor that also holds the follow button.
      let rowNode = null;
      for (let n = a.parentElement, i = 0; n && n !== scroller && i < 6; n = n.parentElement, i++) {
        if (n.querySelector('button')) { rowNode = n; break; }
      }
      const key = uniqueId.toLowerCase();
      let row = bucket.get(key);
      if (!row) { row = blankRow(uniqueId); bucket.set(key, row); changed = true; }
      const scope = rowNode || a;
      const btn = rowNode ? rowNode.querySelector('button') : null;
      const btnText = btn ? (btn.textContent || '').trim() : '';
      if (btnText) {
        const mutual = /friends/i.test(btnText) ? true : /follow/i.test(btnText) ? false : null;
        if (mutual !== null && row.domMutual !== mutual) { row.domMutual = mutual; changed = true; }
      }
      if (!row.nickname) {
        const name = rowTexts(scope).filter(function (t) { return t.toLowerCase() !== key && t !== btnText; })[0];
        if (name) { row.nickname = name; changed = true; }
      }
      if (!row.avatar) {
        const img = scope.querySelector('img');
        if (img && img.src) { row.avatar = img.src; changed = true; }
      }
    });
    if (changed) { debug.dom++; scheduleRender(); }
    pumpStats();
  }

  // Layer 3b: accounts read off the screen have no numbers yet. Pull them from
  // each profile page, one at a time, about one per second.
  let statsBusy = false;
  let statsFails = 0;
  function nextMissing() {
    let found = null;
    buckets.forEach(function (b) {
      if (found) return;
      b.forEach(function (r) { if (!found && !r.hasStats && !r.statsFailed) found = r; });
    });
    return found;
  }
  function parseProfile(html) {
    const m = html.match(/<script[^>]*id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>([\s\S]*?)<\/script>/);
    if (m) {
      try {
        const scope = JSON.parse(m[1]).__DEFAULT_SCOPE__ || {};
        const info = (scope['webapp.user-detail'] || {}).userInfo;
        if (info && info.user && info.stats) return info;
      } catch (e) {}
    }
    const s = html.match(/"stats":(\{[^{}]*"followerCount"[^{}]*\})/);
    if (s) { try { return { user: null, stats: JSON.parse(s[1]) }; } catch (e) {} }
    return null;
  }
  function pumpStats() {
    if (statsBusy || !nativeFetch || statsFails >= 3) return;
    const row = nextMissing();
    if (!row) return;
    statsBusy = true;
    nativeFetch('https://www.tiktok.com/@' + encodeURIComponent(row.uniqueId), { credentials: 'include' })
      .then(function (r) { return r.text(); })
      .then(function (html) {
        const info = parseProfile(html);
        if (!info) throw new Error('no stats');
        // The follow-back flag on a profile page is from the account's side, keep ours.
        const keep = row.relation;
        applyApi(row, info.user || {}, info.stats);
        row.relation = keep;
        if (!info.user) { row.verified = row.verified || false; }
        statsFails = 0;
        debug.profile++;
      })
      .catch(function () { row.statsFailed = true; statsFails++; })
      .then(function () {
        statsBusy = false;
        scheduleRender();
        setTimeout(pumpStats, 900 + Math.random() * 500);
      });
  }

  // ---------------------------------------------------------------------------
  // UI (built with DOM calls only, no innerHTML, so TikTok's CSP doesn't block it)
  // ---------------------------------------------------------------------------
  const state = { view: 'Following', q: '', sort: 'followers-desc', filter: 'all', min: '', max: '', limit: 200, open: false };
  let ui = null;
  let renderTimer = null;
  let scrolling = false;

  function el(tag, css, text) {
    const n = document.createElement(tag);
    if (css) n.style.cssText = css;
    if (text != null) n.textContent = text;
    return n;
  }

  function compact(n) {
    if (n >= 1e9) return (n / 1e9).toFixed(1).replace(/\.0$/, '') + 'B';
    if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M';
    if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'K';
    return String(n);
  }

  function parseNum(v) {
    const m = String(v).trim().toLowerCase().match(/^([\d.,]+)\s*([kmb]?)$/);
    if (!m) return null;
    const n = parseFloat(m[1].replace(/,/g, ''));
    if (isNaN(n)) return null;
    return n * ({ k: 1e3, m: 1e6, b: 1e9 }[m[2]] || 1);
  }

  // Mutual = TikTok's button says Friends, its relation flag says friends (2),
  // or the account shows up in the opposite list if you've loaded it.
  function otherBucket() {
    if (state.view === 'Following') return buckets.get('Followers');
    if (state.view === 'Followers') return buckets.get('Following');
    return null;
  }
  function isMutual(row, other) {
    return row.domMutual === true || row.relation === 2 || !!(other && other.has(row.uniqueId.toLowerCase()));
  }

  const SORTS = {
    'followers-desc': ['Followers, high to low', function (a, b) { return b.followers - a.followers; }],
    'followers-asc': ['Followers, low to high', function (a, b) { return a.followers - b.followers; }],
    'following-desc': ['Following, high to low', function (a, b) { return b.following - a.following; }],
    'likes-desc': ['Likes, high to low', function (a, b) { return b.likes - a.likes; }],
    'videos-desc': ['Videos, most first', function (a, b) { return b.videos - a.videos; }],
    'videos-asc': ['Videos, fewest first', function (a, b) { return a.videos - b.videos; }],
    'ratio-desc': ['Follower/following ratio', function (a, b) { return b.followers / (b.following || 1) - a.followers / (a.following || 1); }],
    'name-asc': ['Username, A to Z', function (a, b) { return a.uniqueId.localeCompare(b.uniqueId); }],
    'order': ['TikTok order (most recent first)', function (a, b) { return a.order - b.order; }],
  };

  const FILTERS = {
    all: 'All',
    mutual: 'Follows back (mutual)',
    notmutual: "Doesn't follow back",
    verified: 'Verified',
    unverified: 'Not verified',
    private: 'Private',
    public: 'Public',
    novideos: 'No videos',
  };

  function currentRows() {
    const bucket = buckets.get(state.view);
    if (!bucket) return [];
    const other = otherBucket();
    const q = state.q.trim().toLowerCase();
    const min = state.min === '' ? null : parseNum(state.min);
    const max = state.max === '' ? null : parseNum(state.max);
    const rows = [];
    bucket.forEach(function (r) {
      if (q && r.uniqueId.toLowerCase().indexOf(q) < 0 && r.nickname.toLowerCase().indexOf(q) < 0) return;
      if (min != null && r.followers < min) return;
      if (max != null && r.followers > max) return;
      const m = isMutual(r, other);
      switch (state.filter) {
        case 'mutual': if (!m) return; break;
        case 'notmutual': if (m) return; break;
        case 'verified': if (!r.verified) return; break;
        case 'unverified': if (r.verified) return; break;
        case 'private': if (!r.isPrivate) return; break;
        case 'public': if (r.isPrivate) return; break;
        case 'novideos': if (!r.hasStats || r.videos > 0) return; break;
      }
      rows.push(r);
    });
    rows.sort(SORTS[state.sort][1]);
    return rows;
  }

  const INPUT_CSS = 'box-sizing:border-box;width:100%;padding:7px 8px;border-radius:6px;border:1px solid #3a3a3a;background:#1c1c1c;color:#eee;font:13px system-ui,sans-serif;';
  const BTN_CSS = 'padding:7px 10px;border-radius:6px;border:1px solid #3a3a3a;background:#262626;color:#eee;font:13px system-ui,sans-serif;cursor:pointer;';

  function select(options, value, onChange) {
    const s = el('select', INPUT_CSS);
    Object.keys(options).forEach(function (k) {
      const o = el('option', '', Array.isArray(options[k]) ? options[k][0] : options[k]);
      o.value = k;
      s.appendChild(o);
    });
    s.value = value;
    s.addEventListener('change', function () { onChange(s.value); });
    return s;
  }

  function input(placeholder, onInput) {
    const i = el('input', INPUT_CSS);
    i.placeholder = placeholder;
    i.addEventListener('input', function () { onInput(i.value); });
    // Keep TikTok's keyboard shortcuts from firing while typing.
    ['keydown', 'keyup', 'keypress'].forEach(function (t) {
      i.addEventListener(t, function (e) { e.stopPropagation(); });
    });
    return i;
  }

  function buildUI() {
    const toggle = el('button', 'position:fixed;right:16px;bottom:16px;z-index:2147483646;padding:10px 14px;border-radius:999px;border:0;background:#fe2c55;color:#fff;font:600 13px system-ui,sans-serif;cursor:pointer;box-shadow:0 4px 14px rgba(0,0,0,.4);', 'Following Filter');
    const panel = el('div', 'position:fixed;top:0;right:0;z-index:2147483647;width:min(430px,100vw);height:100vh;display:none;flex-direction:column;background:#121212;color:#eee;font:13px system-ui,sans-serif;box-shadow:-6px 0 24px rgba(0,0,0,.5);');

    const head = el('div', 'display:flex;align-items:center;gap:8px;padding:12px;border-bottom:1px solid #2a2a2a;');
    const title = el('div', 'flex:1;font-weight:700;font-size:15px;', 'Following Filter');
    const close = el('button', BTN_CSS, 'Close');
    head.appendChild(title);
    head.appendChild(close);

    const controls = el('div', 'display:grid;grid-template-columns:1fr 1fr;gap:8px;padding:12px;border-bottom:1px solid #2a2a2a;');
    const viewSel = el('select', INPUT_CSS);
    viewSel.addEventListener('change', function () { state.view = viewSel.value; state.limit = 200; render(); });
    const search = input('Search name or @username', function (v) { state.q = v; state.limit = 200; scheduleRender(); });
    search.style.gridColumn = '1 / -1';
    const sortSel = select(SORTS, state.sort, function (v) { state.sort = v; render(); });
    const filterSel = select(FILTERS, state.filter, function (v) { state.filter = v; state.limit = 200; render(); });
    const minIn = input('Min followers (e.g. 10k)', function (v) { state.min = v; scheduleRender(); });
    const maxIn = input('Max followers (e.g. 1m)', function (v) { state.max = v; scheduleRender(); });
    filterSel.style.gridColumn = '1 / -1';
    [viewSel, sortSel, filterSel, search, minIn, maxIn].forEach(function (n) { controls.appendChild(n); });

    const actions = el('div', 'display:flex;gap:8px;padding:10px 12px;border-bottom:1px solid #2a2a2a;flex-wrap:wrap;');
    const scrollBtn = el('button', BTN_CSS, 'Auto-load list');
    const csvBtn = el('button', BTN_CSS, 'Export CSV');
    const clearBtn = el('button', BTN_CSS, 'Clear');
    actions.appendChild(scrollBtn);
    actions.appendChild(csvBtn);
    actions.appendChild(clearBtn);

    const status = el('div', 'padding:8px 12px;color:#9a9a9a;font-size:12px;border-bottom:1px solid #2a2a2a;');
    const list = el('div', 'flex:1;overflow-y:auto;overscroll-behavior:contain;');

    [head, controls, actions, status, list].forEach(function (n) { panel.appendChild(n); });

    toggle.addEventListener('click', function () { setOpen(!state.open); });
    close.addEventListener('click', function () { setOpen(false); });
    scrollBtn.addEventListener('click', function () { scrolling ? stopScroll() : startScroll(); });
    csvBtn.addEventListener('click', exportCsv);
    clearBtn.addEventListener('click', function () { buckets.clear(); order = 0; statsFails = 0; render(); });

    ui = { toggle: toggle, panel: panel, viewSel: viewSel, status: status, list: list, scrollBtn: scrollBtn };
    mount();
    setInterval(mount, 2000); // TikTok is a SPA, re-attach if it wipes our nodes
    setInterval(scrapeDom, 1500);
    render();
  }

  function mount() {
    if (!ui || !document.body) return;
    if (!ui.toggle.isConnected) document.body.appendChild(ui.toggle);
    if (!ui.panel.isConnected) document.body.appendChild(ui.panel);
  }

  function setOpen(v) {
    state.open = v;
    ui.panel.style.display = v ? 'flex' : 'none';
    if (v) { scrapeDom(); render(); }
  }

  function scheduleRender() {
    clearTimeout(renderTimer);
    renderTimer = setTimeout(render, 150);
  }

  function totalCount() {
    let n = 0;
    buckets.forEach(function (b) { n += b.size; });
    return n;
  }

  function render() {
    if (!ui) return;
    const total = totalCount();
    ui.toggle.textContent = total ? 'Following Filter (' + total + ')' : 'Following Filter';
    if (!state.open) return;

    // View selector reflects whichever lists have been captured.
    const labels = Array.from(buckets.keys());
    if (labels.length && labels.indexOf(state.view) < 0) state.view = labels[0];
    const want = labels.length ? labels : ['Following'];
    const have = Array.from(ui.viewSel.options).map(function (o) { return o.value + ':' + o.textContent; }).join('|');
    const next = want.map(function (l) { return l + ':' + l + ' (' + ((buckets.get(l) || { size: 0 }).size) + ')'; }).join('|');
    if (have !== next) {
      while (ui.viewSel.firstChild) ui.viewSel.removeChild(ui.viewSel.firstChild);
      want.forEach(function (l) {
        const o = el('option', '', l + ' (' + ((buckets.get(l) || { size: 0 }).size) + ')');
        o.value = l;
        ui.viewSel.appendChild(o);
      });
    }
    ui.viewSel.value = state.view;

    const rows = currentRows();
    const other = otherBucket();
    const bucket = buckets.get(state.view);
    let msg;
    if (!bucket || !bucket.size) {
      msg = 'Nothing captured yet. Open your profile, tap Following, then scroll the list or hit Auto-load list.';
    } else {
      let missing = 0, failed = 0;
      bucket.forEach(function (r) { if (!r.hasStats) { r.statsFailed ? failed++ : missing++; } });
      msg = 'Showing ' + rows.length + ' of ' + bucket.size + '.';
      if (missing && statsFails < 3) msg += ' Fetching stats, ' + missing + ' to go.';
      if (statsFails >= 3) msg += ' TikTok stopped answering stats requests (' + (missing + failed) + ' missing). Press Clear and try again in a few minutes.';
      else if (failed) msg += ' Stats unavailable for ' + failed + '.';
    }
    ui.status.textContent = msg + ' [v1.1 h' + debug.hook + ' r' + debug.replay + ' d' + debug.dom + ' p' + debug.profile + ']';

    while (ui.list.firstChild) ui.list.removeChild(ui.list.firstChild);
    const frag = document.createDocumentFragment();
    rows.slice(0, state.limit).forEach(function (r) { frag.appendChild(rowEl(r, isMutual(r, other))); });
    if (rows.length > state.limit) {
      const more = el('button', BTN_CSS + 'display:block;margin:12px auto;', 'Show more (' + (rows.length - state.limit) + ' left)');
      more.addEventListener('click', function () { state.limit += 200; render(); });
      frag.appendChild(more);
    }
    ui.list.appendChild(frag);
  }

  function badge(text, color) {
    return el('span', 'margin-left:6px;padding:1px 6px;border-radius:999px;font-size:10px;font-weight:600;color:#fff;background:' + color + ';', text);
  }

  function rowEl(r, mutual) {
    const a = el('a', 'display:flex;align-items:center;gap:10px;padding:9px 12px;border-bottom:1px solid #1f1f1f;color:inherit;text-decoration:none;');
    a.href = 'https://www.tiktok.com/@' + encodeURIComponent(r.uniqueId);
    a.target = '_blank';
    a.rel = 'noopener';
    const img = el('img', 'width:40px;height:40px;border-radius:50%;flex:none;background:#2a2a2a;object-fit:cover;');
    if (r.avatar) img.src = r.avatar;
    img.loading = 'lazy';
    img.alt = '';
    const mid = el('div', 'flex:1;min-width:0;');
    const top = el('div', 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600;', '@' + r.uniqueId);
    if (r.verified) top.appendChild(badge('Verified', '#20a4f3'));
    if (r.isPrivate) top.appendChild(badge('Private', '#666'));
    if (mutual) top.appendChild(badge('Mutual', '#1f9d55'));
    const name = el('div', 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#9a9a9a;font-size:12px;', r.nickname);
    const stats = el('div', 'color:#bdbdbd;font-size:12px;margin-top:2px;',
      r.hasStats
        ? compact(r.followers) + ' followers  ·  ' + compact(r.following) + ' following  ·  ' + compact(r.likes) + ' likes  ·  ' + compact(r.videos) + ' videos'
        : (r.statsFailed ? 'Stats unavailable' : 'Stats loading…'));
    mid.appendChild(top);
    mid.appendChild(name);
    mid.appendChild(stats);
    a.appendChild(img);
    a.appendChild(mid);
    return a;
  }

  // ---------------------------------------------------------------------------
  // Auto-load: scrolls TikTok's open list so it keeps loading more accounts.
  // ---------------------------------------------------------------------------
  function startScroll() {
    if (!findScroller()) {
      ui.status.textContent = 'Open your Following (or Followers) list on your profile first, then press Auto-load list.';
      return;
    }
    scrolling = true;
    ui.scrollBtn.textContent = 'Stop loading';
    let last = -1;
    let idle = 0;
    (function tick() {
      if (!scrolling) return;
      const sc = findScroller();
      if (!sc) return stopScroll();
      scrapeDom();
      sc.scrollTop = sc.scrollHeight;
      const now = totalCount() + sc.scrollHeight;
      idle = now === last ? idle + 1 : 0;
      last = now;
      if (idle >= 6) return stopScroll(); // nothing new for a while: reached the end
      setTimeout(tick, 900 + Math.random() * 400);
    })();
  }

  function stopScroll() {
    scrolling = false;
    if (ui) ui.scrollBtn.textContent = 'Auto-load list';
    scrapeDom();
    render();
  }

  // ---------------------------------------------------------------------------
  // CSV export of the current filtered and sorted view
  // ---------------------------------------------------------------------------
  function exportCsv() {
    const rows = currentRows();
    if (!rows.length) return;
    const other = otherBucket();
    const esc = function (v) { return '"' + String(v).replace(/"/g, '""') + '"'; };
    const lines = [['username', 'nickname', 'followers', 'following', 'likes', 'videos', 'verified', 'private', 'mutual', 'url'].join(',')];
    rows.forEach(function (r) {
      const n = function (v) { return r.hasStats ? v : ''; };
      lines.push([esc(r.uniqueId), esc(r.nickname), n(r.followers), n(r.following), n(r.likes), n(r.videos), r.verified, r.isPrivate, isMutual(r, other), esc('https://www.tiktok.com/@' + r.uniqueId)].join(','));
    });
    const blob = new Blob(['' + lines.join('\n')], { type: 'text/csv' });
    const a = el('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'tiktok-' + state.view.toLowerCase().replace(/[^a-z0-9]+/g, '-') + '.csv';
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(function () { URL.revokeObjectURL(a.href); }, 5000);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', buildUI);
  else buildUI();
})();

SHA-256 a700be5c56e71be1dfbe60fbd13c2072675627b3d2ae51140a46886cec5118a6

Latest release