跳到正文
DEV Community· TikTokio·· 5 小時前AI 評分50

如何為 TikTok 單頁應用程式構建精簡的 Manifest V3 擴充功能:從下載按鈕汲取的經驗

Building a tiny Manifest V3 extension for a single-page app (lessons from a TikTok download button)

AI 導讀

TikTokio 的開源 MIT 擴充功能以約 200 行原生 JavaScript,為 TikTok 單頁應用程式加入影片連結按鈕,並將連結交給網站處理。擴充功能以每 800 毫秒檢查網址變化來更新按鈕,並以網址片段傳遞連結,避免連結意外出現在伺服器存取記錄、CDN 記錄或分析來源資訊中。

正文

Disclosure: I work on TikTokio, a free web tool for downloading public TikTok videos. The extension below is open source (MIT) and this post is about how it is built, not a sales pitch. Code: github.com/tiktokio-vn/tiktokio-extension.

Our users kept asking the same thing: "Can I skip the copy-link-paste-link dance?" The website already did the actual work, so the extension only had to do one job well: take the video the user is looking at and hand its link to the website.

That sounds trivial. It mostly is. But a few details were less obvious than expected, especially because TikTok is a single-page app. Here is what we learned, in about 200 lines of vanilla JS and no build step.

The whole extension at a glance

manifest.json        MV3 manifest
background.js        service worker: context menus + opening tabs
common.js            shared helpers (URL checks, URL building)
tiktok-button.js     content script on tiktok.com / douyin.com
autofill.js          content script on our own site
popup.html/js/css    toolbar popup
_locales/en, vi      i18n strings

Permissions are deliberately minimal:

"permissions": ["activeTab", "contextMenus"]

No tabs, no storage, no host permissions beyond the two content-script matches. The fewer permissions you ask for, the less you have to justify in store review, and the less users have to trust you with.

1. Detecting "page changes" in a single-page app

A content script runs once per document load. TikTok rarely does full loads: you scroll, click a video, go back, and the URL changes through the History API while the document stays the same. So run_at: document_idle alone will show the button on the first page and then never update.

There are fancier options (patching history.pushState, listening for popstate, a MutationObserver on the title). We picked the boring one:

let last = location.href;
setInterval(() => {
  if (location.href !== last) {
    last = location.href;
    render();
  }
}, 800);

Why polling?

  • Patching history.pushState from an isolated content script does not patch the page's own history object, because content scripts live in a separate JS world. You would have to inject a script into the main world, which adds complexity and review questions.
  • A MutationObserver on a feed that re-renders constantly fires far more often than every 800 ms.
  • A string comparison every 800 ms costs effectively nothing.

render() is idempotent: it removes the button on non-video pages and adds it (once) on video, photo and story pages:

function isContentPage(href) {
  const u = new URL(href);
  return /\/(video|photo|story)\//.test(u.pathname)
      || /\/(note|share\/video)\//.test(u.pathname);
}

2. Don't touch the site's DOM more than you have to

The button is a single fixed-position element appended to document.documentElement, not inserted into TikTok's markup. TikTok's class names are generated and change often, so anchoring to them would break every few weeks. A floating button with its own ID and its own stylesheet (tiktok-button.css) survives redesigns.

We also set text with textContent (never innerHTML for anything that comes from i18n or the page) and keep the SVG icon as a static string.

3. Context menus that only appear where they make sense

MV3 context menus support URL filters, which keeps the right-click menu clean everywhere else:

chrome.contextMenus.create({
  id: 'tiktokio-link',
  title: chrome.i18n.getMessage('menuLink'),
  contexts: ['link'],
  targetUrlPatterns: ['https://*.tiktok.com/*', 'https://*.douyin.com/*']
});

chrome.contextMenus.create({
  id: 'tiktokio-page',
  title: chrome.i18n.getMessage('menuPage'),
  contexts: ['page', 'video'],
  documentUrlPatterns: ['https://*.tiktok.com/*', 'https://*.douyin.com/*']
});

targetUrlPatterns filters on the link you right-click (useful when someone shares a TikTok link in a chat or a forum). documentUrlPatterns filters on the page you are on. Create menus inside runtime.onInstalled and call removeAll() first, otherwise you get duplicate-ID errors after an update.

4. Passing data to your website: use the hash, not the query string

The background script opens our site with the video link. The obvious way is ?url=.... We used the fragment instead:

buildUrl(link, tool) {
  const params = new URLSearchParams({ link, src: 'ext' });
  return base + path + '#tiktokio-' + params.toString();
}

The fragment is never sent to the server in the request line, so the user's link doesn't end up in access logs, CDN logs or analytics referrers by accident. A small privacy win for zero cost.

On the website side, a tiny content script (autofill.js, only matched on our own domain) reads the hash and immediately removes it so a reload doesn't trigger a second download:

const params = new URLSearchParams(location.hash.slice('#tiktokio-'.length));
history.replaceState(null, '', location.pathname + location.search);

It also re-validates the link with a strict regex before using it. Never trust data from the URL, even when your own extension put it there.

5. Filling a form that a framework controls

Setting input.value = link looks like it works, but many front-end frameworks track input state internally and ignore direct assignments. The reliable approach is to call the native setter and dispatch real events:

const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
setter.call(input, link);
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));

Then submit with form.requestSubmit() rather than form.submit(). requestSubmit() runs validation and fires the submit event, so the site's own JavaScript handler runs exactly as if the user had clicked the button. submit() skips both.

Because the page may still be loading when the script runs, it polls for the form a few times (every 250 ms, giving up after ~10 s) instead of assuming it exists.

6. One shared helper file for the service worker and the popup

MV3 service workers can't use <script> tags, and we didn't want a bundler for 200 lines. common.js defines a plain object and attaches it to self:

const TIKTOKIO = { isSupported(url) { /* ... */ }, guessTool(url) { /* ... */ }, buildUrl() { /* ... */ } };
if (typeof self !== 'undefined') self.TIKTOKIO = TIKTOKIO;

The popup loads it with a normal <script src="common.js">; the service worker loads it with:

if (typeof TIKTOKIO === 'undefined' && typeof importScripts === 'function') importScripts('common.js');

Same code, two contexts, no build step.

7. i18n from day one

All strings live in _locales/en/messages.json and _locales/vi/messages.json, including the extension name and description used by the stores ("name": "__MSG_extName__"). The popup uses data-i18n attributes and one loop:

document.querySelectorAll('[data-i18n]').forEach(el => {
  el.textContent = chrome.i18n.getMessage(el.dataset.i18n);
});

Adding a language later is a JSON file, not a code change.

8. Cross-browser packaging gotchas

The same source runs on Chrome, Edge, Opera, Brave, Cốc Cốc and Firefox, but the Firefox package needed two changes:

  • Firefox requires browser_specific_settings.gecko.id in the manifest.
  • Firefox's MV3 implementation uses background.scripts (an event page) rather than background.service_worker.

We keep one source folder and generate the Firefox manifest.json at packaging time instead of maintaining two copies of the code.

What the extension deliberately does not do

  • It does not download anything itself or talk to TikTok's servers. It only opens a tab.
  • It does not read page content beyond location.href.
  • It has no analytics and no remote code.

That keeps the privacy policy one paragraph long.

A note on responsible use

Tools like this are for saving public videos you have a right to keep (your own uploads, content shared with permission, offline viewing). Please respect creators: credit them, and don't re-upload their work as your own.


If you're building something similar for another single-page site, the patterns above (polling for URL changes, a floating element instead of DOM surgery, hash-based hand-off and native-setter autofill) transfer almost directly. The full source is on GitHub; issues and PRs are welcome.

This post was drafted with AI assistance and checked against the actual source code in the repository.

來源:DEV Community · dev.to