let saveBtn = null;
document.addEventListener('mouseup', () => {
const text = window.getSelection().toString().trim();
if (text.length < 2) {
removeBtn();
return;
}
showBtn(text);
});
function showBtn(text) {
removeBtn();
const range = window.getSelection().getRangeAt(0);
const rect = range.getBoundingClientRect();
// 防止按钮跑到屏幕外面
const btnLeft = Math.min(rect.right + 8, window.innerWidth - 80);
const btnTop = Math.min(rect.bottom + 8, window.innerHeight - 40);
saveBtn = document.createElement('button');
saveBtn.textContent = '收藏';
saveBtn.style.cssText = `
position: fixed;
left: ${btnLeft}px;
top: ${btnTop}px;
z-index: 2147483647;
padding: 4px 10px;
font-size: 13px;
border: none;
border-radius: 4px;
background: #1a73e8;
color: #fff;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,.2);
`;
// 不加这行的话,点按钮会先把选中取消掉
saveBtn.addEventListener('mousedown', (e) => e.preventDefault());
saveBtn.addEventListener('click', async () => {
await saveQuote(text);
removeBtn();
showToast('已收藏');
});
document.body.appendChild(saveBtn);
}
function removeBtn() {
if (saveBtn) {
saveBtn.remove();
saveBtn = null;
}
}
async function saveQuote(text) {
const { quotes = [] } = await chrome.storage.local.get('quotes');
quotes.unshift({
id: Date.now(),
text,
title: document.title,
url: location.href,
time: new Date().toLocaleString()
});
await chrome.storage.local.set({ quotes: quotes.slice(0, 100) });
}
function showToast(msg) {
const toast = document.createElement('div');
toast.textContent = msg;
toast.style.cssText = `
position: fixed; top: 20px; right: 20px; z-index: 2147483647;
background: #333; color: #fff; padding: 8px 16px;
border-radius: 4px;
`;
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 1500);
}
// 页面滚动了,按钮位置会飘,干脆去掉
document.addEventListener('scroll', removeBtn, true);