跳至主要内容

2 篇文章 含有標籤「Chrome Extension」

檢視所有標籤

Chrome Extension 入門教學筆記 | 學習筆記

· 閱讀時間約 3 分鐘
kdchang

前言

Chrome Extension(Chrome 擴充功能)是針對 Google Chrome 瀏覽器開發的瀏覽器插件,能夠延伸瀏覽器的功能,提供更高效的使用體驗。你可以用它來自動化操作、強化 UI、增加捷徑、記錄內容、攔截請求等等。

本教學將介紹 Chrome Extension 的基本架構、開發流程與一個簡單的實作範例,協助你快速入門。


重點摘要

  1. 基本架構:

    • manifest.json:擴充功能的核心設定檔
    • background.js / service_worker.js:背景邏輯(例如攔截請求、常駐任務)
    • popup.html + popup.js:點擊圖示後的互動 UI
    • content.js:注入頁面的腳本,直接與 DOM 互動
  2. 開發步驟:

    • 建立資料夾結構與設定檔
    • 撰寫功能腳本與 UI
    • 在 Chrome 中載入未封裝的擴充功能
    • 測試與除錯
  3. 核心權限與功能:

    • permissions 欄位需指定所需功能(如 tabs, storage, scripting
    • host_permissions 控制哪些網站允許注入腳本
    • 可與頁面雙向通訊
  4. 常見用途:

    • 提高生產力(截圖、標記、翻譯)
    • 資料擷取與分析(網頁爬蟲輔助)
    • 儲存內容(書籤、待辦清單)
    • 網站 UI 客製化

實際範例:儲存選取文字的小擴充功能

功能簡介

當使用者在網頁上選取一段文字並點擊擴充功能圖示,會將選取的文字儲存到 localStorage,方便後續檢視。


1. 專案結構

my-extension/
├── manifest.json
├── popup.html
├── popup.js
├── content.js

2. manifest.json

{
"manifest_version": 3,
"name": "Save Selected Text",
"version": "1.0",
"description": "儲存網頁中選取的文字",
"permissions": ["scripting", "storage"],
"host_permissions": ["<all_urls>"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
},
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}

3. popup.html

<!DOCTYPE html>
<html>
<head>
<title>已儲存文字</title>
</head>
<body>
<h3>你儲存的文字:</h3>
<ul id="text-list"></ul>
<script src="popup.js"></script>
</body>
</html>

4. popup.js

document.addEventListener('DOMContentLoaded', async () => {
chrome.storage.local.get(['savedTexts'], (result) => {
const list = document.getElementById('text-list');
const texts = result.savedTexts || [];
texts.forEach((text) => {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
});
});
});

5. content.js

document.addEventListener('mouseup', () => {
const selectedText = window.getSelection().toString().trim();
if (selectedText) {
chrome.storage.local.get(['savedTexts'], (result) => {
const current = result.savedTexts || [];
current.push(selectedText);
chrome.storage.local.set({ savedTexts: current });
});
}
});

6. 載入擴充功能

  1. 打開 Chrome 瀏覽器
  2. 前往 chrome://extensions/
  3. 開啟右上角「開發人員模式」
  4. 點選「載入未封裝項目」
  5. 選取專案資料夾(my-extension)

7. 測試方式

  1. 任意打開一個網頁
  2. 選取文字後放開滑鼠
  3. 點擊瀏覽器右上角的擴充功能圖示
  4. 在彈出的視窗中查看剛才儲存的文字

小技巧與補充

  • 使用 TypeScript:可結合 Vitewebpack 實現模組化開發。
  • Hot Reload:透過專案如 crxjs 可達成自動刷新套件。
  • 權限最小化原則:僅使用必要權限以通過審核。
  • Storage API:可選擇使用 localStoragechrome.storage.localsync 等不同儲存方式。
  • message passing:背景與 content script 可用 chrome.runtime.sendMessage 溝通。

總結

Chrome Extension 是一個強大的平台,讓開發者能以 HTML、CSS、JavaScript 等前端技術打造自己的工具。無論是為了解決個人需求、改善使用體驗,還是作為產品 MVP 的雛型開發平台,Chrome Extension 都是值得投資時間學習的技術。

從簡單的文字儲存開始,你可以慢慢拓展功能,加入右鍵選單、快捷鍵、網頁改寫、API 串接等高階應用,打造出屬於你自己的瀏覽器擴充小工具。

chrome.storage.local vs. localStorage:資料儲存方式差異入門教學筆記 | 學習筆記

· 閱讀時間約 4 分鐘
kdchang

前言

在前端與 Chrome 擴充功能(Chrome Extension)開發中,「資料儲存」是一項常見需求。開發者常見的兩種方式為:

  • localStorage:瀏覽器原生提供的本地儲存 API
  • chrome.storage.local:Chrome Extension 提供的本地儲存 API

兩者名稱相似,功能也都能儲存 key-value 結構資料,但其用途、行為、效能與限制卻有顯著差異。本篇筆記將帶你掌握這兩者的差別,並透過實作範例協助你在開發時做出正確選擇。


重點摘要

1. 定義與使用場景

  • localStorage 是 Web API,適用於一般網頁與 Content Script,操作簡便但同步。
  • chrome.storage.local 是專為 Chrome 擴充功能設計的非同步儲存 API,適用於 Background、Popup、Options、Content Script 等擴充功能組件。

2. 主要差異比較

項目chrome.storage.locallocalStorage
API 類型非同步同步
儲存容量約 5MB 以上,可依平台調整約 5MB(視瀏覽器而定)
使用範圍限於 Chrome Extension網頁與 Content Script
安全性與隔離性高(與其他網站與擴充隔離)中(每個 domain 隔離)
可與 background/popup 共用
是否支援跨裝置同步使用 chrome.storage.sync 可支援

3. 實作差異

  • localStorage 使用方式簡單、同步,可立即取得值。
  • chrome.storage.local 是非同步設計,需透過 callback 或 Promise 取得值。

實際範例比較

以下為兩者的典型儲存與讀取操作實作方式。


一、使用 localStorage(同步)

儲存資料

localStorage.setItem('username', 'kdchang');

讀取資料

const name = localStorage.getItem('username');
console.log(name); // 輸出:kdchang

刪除資料

localStorage.removeItem('username');

優點與限制

  • 優點:簡單、直覺、無需 callback
  • 限制:無法在 background script 中使用、同步操作可能阻塞 UI、無跨 component 溝通機制

二、使用 chrome.storage.local(非同步)

儲存資料

chrome.storage.local.set({ username: 'kdchang' }, () => {
console.log('儲存成功');
});

讀取資料

chrome.storage.local.get(['username'], (result) => {
console.log('讀到的值:', result.username);
});

刪除資料

chrome.storage.local.remove('username', () => {
console.log('已刪除 username');
});

優點與限制

  • 優點:資料與擴充功能隔離、安全性高、能跨組件共享
  • 限制:需處理非同步流程(可用 async/await 解決)

實戰應用:擴充功能記錄使用者偏好設定

專案背景

你開發了一個可自訂主題配色的擴充功能,使用者可以切換「深色」或「淺色」模式,並希望記錄下來。


localStorage 實作方式(限 Content Script)

// 儲存使用者偏好
localStorage.setItem('theme', 'dark');

// 頁面載入時讀取
const theme = localStorage.getItem('theme');
document.body.setAttribute('data-theme', theme);

此方法雖然簡便,但無法在 background script、popup 等元件中共用。


chrome.storage.local 實作方式(推薦)

// 儲存
chrome.storage.local.set({ theme: 'dark' }, () => {
console.log('儲存主題成功');
});

// 讀取
chrome.storage.local.get(['theme'], (result) => {
document.body.setAttribute('data-theme', result.theme || 'light');
});

這種方式可讓 background.js、popup.html、options.html 都能取得相同資料,並透過 message passing 進一步溝通。


使用建議與最佳實踐

選擇依據:

  • Chrome Extension 專案開發時:建議一律使用 chrome.storage.local,搭配 async/await 管理非同步流程。
  • Content Script 或網頁前端小工具:若不考慮擴充功能架構,可使用 localStorage 快速開發。

注意事項:

  • chrome.storage.local 每次寫入都是非同步,避免過度頻繁更新(例如輸入框每秒觸發)
  • localStorage 資料若寫入太大或格式不當,可能造成同步錯誤或被清除

總結

問題建議做法
在 popup、background、content script 共享設定資料使用 chrome.storage.local
快速暫存使用者動作、不需跨頁可用 localStorage
需考慮非同步、可擴充、跨頁共享與安全性優先使用 chrome.storage.local

chrome.storage.locallocalStorage 各有適用場景與特點,選擇時需考量使用環境、效能、安全性與 API 特性。透過本文你應該能更清楚何時該用哪一種方式,並應用在擴充功能與網頁開發中,打造穩定且高效的儲存邏輯。