有这么一个需求,就是经常要复制某些网站的资料存到word、txt、或者excel中
反复切换浏览器比较麻烦,思索再三,开发了一个浏览器插件
取名为“速记超人记事本”
功能如下:
当我复制网页内容的时候会自动存储到浏览器插件中,如图:
记录的内容自动存储到插件中,可以删除,编辑搜索,也可以导出为excel,txt格式
这样我们就可以直接愉快的ctrl+c了,待我复制完成后,一键导出就可以了
之前做了个1.0版本,网友反应增加一些编辑功能,索性重做了一版,可以在谷歌内核浏览器下使用。
贴上代码吧:
background.js
// 初始化扩展状态
chrome.runtime.onInstalled.addListener(function() {
console.log('扩展已安装,初始化状态');
chrome.storage.local.set({ enabled: true, notes: [] }, function() {
console.log('初始化完成');
debugStorage();
});
});
// 监听消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log('后台收到消息:', message);
if (message.action === 'toggleExtension') {
// 处理扩展开关状态变化
handleExtensionToggle(message.enabled);
sendResponse({status: 'toggled', enabled: message.enabled});
} else if (message.action === 'saveCopiedContent') {
console.log('保存复制内容:', message.content.substring(0, 20) + '...');
saveNote(message.content, sender.tab ? sender.tab.url : 'unknown');
sendResponse({status: 'saved'});
}
return true; // 保持消息通道开放以进行异步响应
});
// 处理扩展开关状态变化
function handleExtensionToggle(enabled) {
console.log('扩展状态切换为:', enabled ? '启用' : '禁用');
// 通知所有内容脚本
chrome.tabs.query({}, function(tabs) {
for (let tab of tabs) {
try {
chrome.tabs.sendMessage(tab.id, {
action: enabled ? 'enableCopyListener' : 'disableCopyListener'
});
} catch (err) {
console.error('向标签页发送消息失败:', err);
}
}
});
}
// 保存复制的内容
function saveNote(content, url) {
chrome.storage.local.get('notes', function(data) {
let notes = data.notes || [];
// 创建新笔记
const newNote = {
id: Date.now().toString(),
content: content,
url: url,
timestamp: new Date().toISOString()
};
console.log('创建新笔记:', newNote);
// 添加到笔记列表
notes.unshift(newNote);
// 保存到存储
chrome.storage.local.set({ notes: notes }, function() {
console.log('笔记已保存到存储,总数:', notes.length);
// 显示通知
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon48.png',
title: '复制笔记',
message: '已保存复制的内容'
});
// 通知popup页面(如果打开)刷新数据
chrome.runtime.sendMessage({ action: 'noteAdded' })
.catch(() => console.log('Popup可能未打开,无法通知'));
});
});
}
console.log('后台脚本已加载');
// 在background.js顶部添加调试函数
function debugStorage() {
chrome.storage.local.get(null, function(data) {
console.log('当前存储的所有数据:', data);
if (data.notes) {
console.log('笔记总数:', data.notes.length);
if (data.notes.length > 0) {
console.log('最新笔记:', data.notes[0]);
}
} else {
console.log('没有找到笔记数据');
}
});
}
contentScript.js
// 标记是否已经设置了监听器
let listenerActive = false;
// 设置复制事件监听器
function setupCopyListener() {
if (listenerActive) return;
document.addEventListener('copy', handleCopy);
console.log('复制监听器已设置');
listenerActive = true;
}
// 移除复制事件监听器
function removeCopyListener() {
document.removeEventListener('copy', handleCopy);
console.log('复制监听器已移除');
listenerActive = false;
}
// 处理复制事件
function handleCopy(e) {
// 获取选中的文本
const selectedText = window.getSelection().toString().trim();
if (selectedText) {
console.log('检测到复制内容:', selectedText.substring(0, 20) + (selectedText.length > 20 ? '...' : ''));
console.log('当前页面URL:', window.location.href);
// 发送消息到后台脚本
chrome.runtime.sendMessage({
action: 'saveCopiedContent',
content: selectedText
}, function(response) {
if (response) {
console.log('发送复制内容到后台,响应:', response);
} else {
console.error('发送消息失败,可能是后台脚本未响应');
// 尝试重新连接
chrome.runtime.connect().onDisconnect.addListener(function() {
console.log('尝试重新连接后台脚本');
});
}
});
}
}
// 检查扩展是否启用
chrome.storage.local.get('enabled', function(data) {
console.log('扩展状态:', data.enabled !== false ? '已启用' : '已禁用');
if (data.enabled !== false) {
setupCopyListener();
}
});
// 监听来自后台脚本的消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log('收到消息:', message);
if (message.action === 'disableCopyListener') {
removeCopyListener();
sendResponse({status: 'disabled'});
} else if (message.action === 'enableCopyListener') {
setupCopyListener();
sendResponse({status: 'enabled'});
}
return true; // 保持消息通道开放以进行异步响应
});
// 初始设置监听器
setupCopyListener();
console.log('内容脚本已加载');
manifest.json
{
"manifest_version": 3,
"name": "速记超人记事本",
"version": "1.0",
"description": "自动保存复制的内容,记录时间、内容和网站",
"permissions": [
"storage",
"tabs",
"scripting",
"notifications",
"clipboardRead"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"],
"run_at": "document_end"
}
],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
popup.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>复制笔记</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Microsoft YaHei', sans-serif;
}
body {
width: 400px;
min-height: 500px;
padding: 15px;
background-color: #f5f5f5;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid #ddd;
}
h1 {
font-size: 18px;
color: #333;
}
.switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
}
.search-container {
display: flex;
margin-bottom: 15px;
}
.search-container input {
flex: 1;
padding: 8px;
border: 1px solid #ddd;
outline: none;
}
.search-container button {
padding: 8px 12px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin-left: 5px;
}
.controls {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
}
.sort-options select {
padding: 6px;
border: 1px solid #ddd;
}
.export-options button {
padding: 6px 12px;
margin-left: 5px;
background-color: #2196F3;
color: white;
border: none;
cursor: pointer;
}
.export-options button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.notes-container {
max-height: 350px;
overflow-y: auto;
margin-bottom: 15px;
}
.note-item {
background-color: white;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.note-header {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
font-size: 12px;
color: #666;
}
.note-content {
margin-bottom: 10px;
word-break: break-all;
}
.note-actions {
display: flex;
justify-content: flex-end;
}
.note-actions button {
padding: 4px 8px;
margin-left: 5px;
background-color: #f1f1f1;
border: 1px solid #ddd;
cursor: pointer;
}
.note-actions button:hover {
background-color: #e1e1e1;
}
.pagination {
display: flex;
justify-content: center;
}
.pagination button {
padding: 5px 10px;
margin: 0 2px;
border: 1px solid #ddd;
background-color: white;
cursor: pointer;
}
.pagination button.active {
background-color: #2196F3;
color: white;
border-color: #2196F3;
}
.empty-state {
text-align: center;
padding: 30px 0;
color: #666;
}
.edit-modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.modal-content {
background-color: white;
padding: 20px;
width: 80%;
max-width: 350px;
}
.modal-content textarea {
width: 100%;
height: 100px;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ddd;
resize: none;
}
.modal-actions {
display: flex;
justify-content: flex-end;
}
.modal-actions button {
padding: 6px 12px;
margin-left: 10px;
cursor: pointer;
}
.modal-actions .save {
background-color: #4CAF50;
color: white;
border: none;
}
.modal-actions .cancel {
background-color: #f1f1f1;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<header>
<h1>复制笔记</h1>
<label class="switch">
<input type="checkbox" id="enableSwitch">
<span class="slider"></span>
</label>
</header>
<div class="search-container">
<input type="text" id="searchInput" placeholder="搜索笔记...">
<button id="searchBtn">搜索</button>
</div>
<div class="controls">
<div class="sort-options">
<select id="sortSelect">
<option value="time-desc">时间 (新→旧)</option>
<option value="time-asc">时间 (旧→新)</option>
<option value="content-asc">内容 (A→Z)</option>
<option value="content-desc">内容 (Z→A)</option>
<option value="url-asc">网站 (A→Z)</option>
<option value="url-desc">网站 (Z→A)</option>
</select>
</div>
<div class="export-options">
<button id="exportExcel" disabled>导出Excel</button>
<button id="exportTxt" disabled>导出TXT</button>
</div>
</div>
<div class="notes-container" id="notesContainer">
<div class="empty-state">暂无笔记</div>
</div>
<div class="pagination" id="pagination"></div>
<div class="edit-modal" id="editModal">
<div class="modal-content">
<textarea id="editContent"></textarea>
<div class="modal-actions">
<button class="cancel" id="cancelEdit">取消</button>
<button class="save" id="saveEdit">保存</button>
</div>
</div>
</div>
<script src="popup.js"></script>
</body>
</html>
popup.js
let notes = [];
let currentPage = 1;
const notesPerPage = 10;
let currentSort = 'time-desc';
let searchQuery = '';
let editingNoteId = null;
// 初始化
document.addEventListener('DOMContentLoaded', function() {
console.log('Popup页面已加载');
// 每次打开popup时,强制从storage获取最新数据
chrome.storage.local.get('notes', function(data) {
console.log('加载笔记数据:', data);
if (data.notes && Array.isArray(data.notes)) {
notes = data.notes;
console.log('找到', notes.length, '条笔记');
updateExportButtons();
renderNotes();
} else {
console.log('没有找到笔记数据或格式不正确');
notes = [];
renderEmptyState();
}
});
setupEventListeners();
checkExtensionStatus();
});
// 设置事件监听器
function setupEventListeners() {
// 开关功能
document.getElementById('enableSwitch').addEventListener('change', toggleExtension);
// 搜索功能
document.getElementById('searchBtn').addEventListener('click', searchNotes);
document.getElementById('searchInput').addEventListener('keyup', function(e) {
if (e.key === 'Enter') {
searchNotes();
}
});
// 排序功能
document.getElementById('sortSelect').addEventListener('change', function() {
currentSort = this.value;
renderNotes();
});
// 导出功能
document.getElementById('exportExcel').addEventListener('click', exportToExcel);
document.getElementById('exportTxt').addEventListener('click', exportToTxt);
// 编辑模态框
document.getElementById('cancelEdit').addEventListener('click', closeEditModal);
document.getElementById('saveEdit').addEventListener('click', saveEditedNote);
// 监听来自后台的消息
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log('Popup收到消息:', message);
if (message.action === 'noteAdded') {
console.log('检测到新笔记添加,刷新数据');
loadNotes();
sendResponse({status: 'refreshed'});
}
return true; // 保持消息通道开放以进行异步响应
});
}
// 检查扩展状态
function checkExtensionStatus() {
chrome.storage.local.get('enabled', function(data) {
document.getElementById('enableSwitch').checked = data.enabled !== false;
});
}
// 切换扩展状态
function toggleExtension() {
const enabled = document.getElementById('enableSwitch').checked;
chrome.storage.local.set({ enabled: enabled });
// 通知后台脚本状态变化
chrome.runtime.sendMessage({ action: 'toggleExtension', enabled: enabled }, function(response) {
console.log('扩展状态已切换,响应:', response);
});
}
// 渲染笔记
function renderNotes() {
const container = document.getElementById('notesContainer');
container.innerHTML = '';
// 过滤笔记
let filteredNotes = filterNotes();
// 排序笔记
sortNotes(filteredNotes);
// 如果没有笔记,显示空状态
if (filteredNotes.length === 0) {
renderEmptyState();
return;
}
// 计算分页
const totalPages = Math.ceil(filteredNotes.length / notesPerPage);
if (currentPage > totalPages) {
currentPage = totalPages;
}
const startIndex = (currentPage - 1) * notesPerPage;
const endIndex = Math.min(startIndex + notesPerPage, filteredNotes.length);
const currentNotes = filteredNotes.slice(startIndex, endIndex);
// 渲染当前页的笔记
currentNotes.forEach(note => {
const noteElement = createNoteElement(note);
container.appendChild(noteElement);
});
// 渲染分页
renderPagination(totalPages);
}
// 过滤笔记
function filterNotes() {
if (!searchQuery) {
return [...notes];
}
const query = searchQuery.toLowerCase();
return notes.filter(note =>
note.content.toLowerCase().includes(query) ||
note.url.toLowerCase().includes(query)
);
}
// 排序笔记
function sortNotes(notesToSort) {
switch (currentSort) {
case 'time-desc':
notesToSort.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
break;
case 'time-asc':
notesToSort.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
break;
case 'content-asc':
notesToSort.sort((a, b) => a.content.localeCompare(b.content));
break;
case 'content-desc':
notesToSort.sort((a, b) => b.content.localeCompare(a.content));
break;
case 'url-asc':
notesToSort.sort((a, b) => a.url.localeCompare(b.url));
break;
case 'url-desc':
notesToSort.sort((a, b) => b.url.localeCompare(a.url));
break;
}
}
// 创建笔记元素
function createNoteElement(note) {
const noteDiv = document.createElement('div');
noteDiv.className = 'note-item';
noteDiv.dataset.id = note.id;
const header = document.createElement('div');
header.className = 'note-header';
const time = document.createElement('span');
time.textContent = formatDate(note.timestamp);
const url = document.createElement('span');
url.textContent = formatUrl(note.url);
url.title = note.url;
header.appendChild(time);
header.appendChild(url);
const content = document.createElement('div');
content.className = 'note-content';
content.textContent = note.content;
const actions = document.createElement('div');
actions.className = 'note-actions';
const editBtn = document.createElement('button');
editBtn.textContent = '编辑';
editBtn.addEventListener('click', () => openEditModal(note));
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '删除';
deleteBtn.addEventListener('click', () => deleteNote(note.id));
actions.appendChild(editBtn);
actions.appendChild(deleteBtn);
noteDiv.appendChild(header);
noteDiv.appendChild(content);
noteDiv.appendChild(actions);
return noteDiv;
}
// 渲染空状态
function renderEmptyState() {
const container = document.getElementById('notesContainer');
container.innerHTML = '<div class="empty-state">暂无笔记</div>';
// 隐藏分页
document.getElementById('pagination').innerHTML = '';
}
// 渲染分页
function renderPagination(totalPages) {
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
if (totalPages <= 1) {
return;
}
// 上一页按钮
if (currentPage > 1) {
const prevBtn = document.createElement('button');
prevBtn.textContent = '上一页';
prevBtn.addEventListener('click', () => {
currentPage--;
renderNotes();
});
pagination.appendChild(prevBtn);
}
// 页码按钮
for (let i = 1; i <= totalPages; i++) {
const pageBtn = document.createElement('button');
pageBtn.textContent = i;
if (i === currentPage) {
pageBtn.classList.add('active');
}
pageBtn.addEventListener('click', () => {
currentPage = i;
renderNotes();
});
pagination.appendChild(pageBtn);
}
// 下一页按钮
if (currentPage < totalPages) {
const nextBtn = document.createElement('button');
nextBtn.textContent = '下一页';
nextBtn.addEventListener('click', () => {
currentPage++;
renderNotes();
});
pagination.appendChild(nextBtn);
}
}
// 搜索笔记
function searchNotes() {
searchQuery = document.getElementById('searchInput').value.trim();
currentPage = 1;
renderNotes();
}
// 删除笔记
function deleteNote(id) {
if (confirm('确定要删除这条笔记吗?')) {
notes = notes.filter(note => note.id !== id);
saveNotes();
renderNotes();
updateExportButtons();
}
}
// 打开编辑模态框
function openEditModal(note) {
editingNoteId = note.id;
document.getElementById('editContent').value = note.content;
document.getElementById('editModal').style.display = 'flex';
}
// 关闭编辑模态框
function closeEditModal() {
document.getElementById('editModal').style.display = 'none';
editingNoteId = null;
}
// 保存编辑后的笔记
function saveEditedNote() {
const content = document.getElementById('editContent').value.trim();
if (!content) {
alert('笔记内容不能为空');
return;
}
const noteIndex = notes.findIndex(note => note.id === editingNoteId);
if (noteIndex !== -1) {
notes[noteIndex].content = content;
saveNotes();
renderNotes();
closeEditModal();
}
}
// 保存笔记到存储
function saveNotes() {
chrome.storage.local.set({ notes: notes }, function() {
console.log('笔记已保存到存储,总数:', notes.length);
});
updateExportButtons();
}
// 更新导出按钮状态
function updateExportButtons() {
const hasNotes = notes.length > 0;
document.getElementById('exportExcel').disabled = !hasNotes;
document.getElementById('exportTxt').disabled = !hasNotes;
}
// 导出为Excel
function exportToExcel() {
if (notes.length === 0) {
return;
}
// 创建CSV内容
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "时间,内容,网站\n";
notes.forEach(note => {
const time = formatDate(note.timestamp);
const content = note.content.replace(/"/g, '""'); // 转义双引号
const url = note.url;
csvContent += `"${time}","${content}","${url}"\n`;
});
// 创建下载链接
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "复制笔记_" + formatDateForFilename(new Date()) + ".csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// 导出为TXT
function exportToTxt() {
if (notes.length === 0) {
return;
}
// 创建TXT内容
let txtContent = "";
notes.forEach(note => {
const time = formatDate(note.timestamp);
txtContent += `时间: ${time}\n`;
txtContent += `内容: ${note.content}\n`;
txtContent += `网站: ${note.url}\n`;
txtContent += "------------------------\n\n";
});
// 创建下载链接
const blob = new Blob([txtContent], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", "复制笔记_" + formatDateForFilename(new Date()) + ".txt");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
// 格式化日期
function formatDate(timestamp) {
const date = new Date(timestamp);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
// 格式化URL(截取域名)
function formatUrl(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch (e) {
return url;
}
}
// 格式化日期用于文件名
function formatDateForFilename(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hour = String(date.getHours()).padStart(2, '0');
const minute = String(date.getMinutes()).padStart(2, '0');
return `${year}${month}${day}_${hour}${minute}`;
}
// 加载笔记
function loadNotes() {
chrome.storage.local.get('notes', function(data) {
console.log('加载笔记数据:', data);
if (data.notes && Array.isArray(data.notes)) {
notes = data.notes;
console.log('找到', notes.length, '条笔记');
updateExportButtons();
renderNotes();
} else {
console.log('没有找到笔记数据或格式不正确');
notes = [];
renderEmptyState();
}
});
}
转载请注明出处,盗用可耻