Unlocking Browser Extension Power: Real‑World Scenarios and Implementation Guides
This article explores browser extension use cases—from product capabilities and data‑collection tools to daily utilities—provides detailed implementation ideas for each scenario, and walks through concrete code examples such as traffic recording, behavior analysis, and proxy plugins, helping developers build practical, production‑ready Chrome extensions.
Overview
The article starts by introducing browser extension application scenarios, interleaving basic capabilities and common entry points, and aims to answer three core questions: where can extensions be used, what are the main implementation ideas for different scenarios, and how to develop a practical, usable browser extension.
1. Extension Application Scenarios
1.1 As a Product Capability
PTS Traffic Recording Plugin PTS is a cloud performance‑testing product. The plugin records API request sequences during user interactions and generates test scenarios with one click, greatly improving usability.
UI Cloud Test Recording Plugin UI Cloud Test is a front‑end UI automation platform. Its plugin records user operations on pages, lowering the barrier for writing automation scripts.
AEM Heatmap Plugin Provides click/exposure heatmaps for AEM sites, allowing real‑time analysis directly on target pages.
Juejin (稀土掘金) Plugin A background‑page plugin that syncs login state and drives traffic to Juejin sites, increasing user stickiness.
1.2 Behavior Analysis Tools
Behavior Analysis Plugin Collects cross‑site user behavior data (device performance, navigation paths) to inform product evolution.
1.3 As a Product Carrier
Sider Implements an AI assistant via Chrome's native siderPanel; low resource consumption but limited compatibility.
Monica Injects a side panel using content scripts; better compatibility but higher resource usage.
Note‑Taking Plugins Inject DOM elements to allow users to write notes on any webpage.
1.4 Daily Utility Tools
Webpage Translation Extracts TextNodes, translates them, and writes back the results.
Color Picker Gets the CSS color property of a clicked element via getComputedStyle.
OneTab Manages tabs and aggregates navigation using chrome.tabs and chrome.topSites APIs.
Chat Communication Uses the plugin as a carrier to send notifications across tabs or the desktop.
1.5 Developer Tools
XSwitch A proxy plugin for front‑end developers that intercepts specific requests and redirects them locally using chrome.webRequest.
React Developer Tools Provides a persistent devtool panel for React component state analysis.
Formily DevTools Offers a devtool panel for Formily state inspection.
1.6 Others
Cookie Hijack Highlights security risks where malicious plugins can read any site’s cookies.
Request Hijack – E‑commerce Rebate Describes gray‑market plugins that inject referral info into e‑commerce requests.
Chrome Theme Skins Manages Chrome theme skins, a common capability for VS Code‑style extensions.
2. Practical Cases
2.1 PTS Traffic Recording Plugin
Business background: PTS requires API orchestration, which is a high barrier for users. The plugin records request sequences and generates test scenarios automatically.
setInterval(() => { try { const manifest = chrome.extension.getURL('manifest.json'); Promise.all([fetch(manifest), fetch('https://xx.com/pts-record-chrome-plugin/package.json')]) .then(res => [res[0].json(), res[1].json()]) .then(result => Promise.all([result[0], result[1]])) .then(res => [res[0].version, res[1].version]) .then(versions => { const [currentVersion, latestVersion] = versions; if (compareVersion(latestVersion, currentVersion) > 0) { storage.set('hasNew', latestVersion); } else { storage.set('hasNew', false); } }) .catch(() => { storage.set('hasNew', false); }); } catch (error) { storage.set('hasNew', false); } }, 1000 * 60);Key implementation points: traffic recording, selective request type filtering (GET/POST), and capturing request headers via chrome.webRequest.
chrome.webRequest.onBeforeRequest.addListener(handleBeforeRequest, { urls: ['<all_urls>'] }, ['requestBody', 'blocking', 'extraHeaders']); chrome.webRequest.onBeforeSendHeaders.addListener(handleBeforeSendHeaders, { urls: ['<all_urls>'] }, ['requestHeaders', 'blocking', 'extraHeaders']); chrome.webRequest.onBeforeRedirect.addListener(handleOnBeforeRedirect, { urls: ['<all_urls>'] }); chrome.webRequest.onCompleted.addListener(handleOnCompleted, { urls: ['<all_urls>'] }, ['responseHeaders', 'extraHeaders']); chrome.runtime.onMessage.addListener(handleRuntimeMessage); // XHR hijack
const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function () { this.addEventListener('readystatechange', function () { if (this.readyState === 4) { window.top.postMessage({ direction: 'from-page-monkey-patch-script', response: 'response', value: { body: handleResponse(this), responseUrl: this.responseURL } }, '*'); } }, false); send.apply(this, arguments); };
// fetch hijack
const originalFetch = window.fetch;
window.fetch = function () { return new Promise((resolve, reject) => { originalFetch.apply(this, arguments).then(response => { const clone = response.clone(); clone.text().then(text => { window.top.postMessage({ direction: 'from-page-monkey-patch-script', response: 'fetch', value: { body: text, responseUrl: response.url } }, '*'); resolve(response); }); }).catch(err => { reject(err); }); }); };2.2 Behavior Analysis Plugin
Collects user operation data (page visits, clicks) and reports it for product improvement. It synchronizes user identity via messages and uses AES tracking SDK.
import { MessageTarget, MessageType } from '../../contstants/message';
export const ticketEventhandler = (e) => { if (e.target === MessageTarget.IntelligentAssistantBackgroundScript && e.origin === MessageTarget.IntelligentAssistantContentScript) { if (e.type === MessageType.UidEvent) { if (e.data?.uid !== (window as any)?.aes?.getConfig('uid')) { (window as any)?.aes?.setConfig?.({ uid: e.data?.uid }); } } } }; const useVersions = () => { const [versions, setVersions] = useState({}); useEffect(() => { chrome.storage.local.get(['currentVersion'], ({ currentVersion }) => { updateConfigInfo().then(res => { setVersions({ currentVersion, hasNew: res?.version !== currentVersion }); }); }); }, []); return versions; }; // AES initialization
import { initAES } from './aes/index';
initAES();2.3 XSwitch Proxy Plugin
Provides a front‑end development proxy that intercepts requests and redirects them locally, breaking CORS limitations.
chrome.webRequest.onBeforeRequest.addListener(function (details) { if (forward[constants["s"]] !== enums["b"].NO) { if (clearCacheEnabled) { clearCache(); } return forward.onBeforeRequestCallback(details); } return {}; }, { urls: [constants["c"]] }, [constants["e"]]);
chrome.webRequest.onHeadersReceived.addListener(headersReceivedListener, { urls: [constants["c"]] }, [constants["e"], constants["O"]]);
chrome.webRequest.onBeforeSendHeaders.addListener(function (details) { return forward.onBeforeSendHeadersCallback(details); }, { urls: [constants["c"]] }, [constants["e"], constants["N"]]);3. Summary
From a business perspective, extensions serve as product capabilities (traffic/operation recorders), product enhancers (heatmaps, referral tools), and carriers (AI assistants, note‑taking). From an efficiency perspective, they reduce R&D cost and aid debugging (React DevTools, Formily DevTools, XSwitch). From an individual developer view, they enable utilities such as skinning, tab aggregation, translation, and more. The article concludes with actionable directions for building practical, production‑ready browser extensions.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Alibaba Cloud Developer
Alibaba's official tech channel, featuring all of its technology innovations.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
