work/mvp/browser-extension/content/content.js
2025-12-17 22:30:44 +08:00

54 lines
1.4 KiB
JavaScript

// 内容脚本 - 在网页中运行
console.log('浏览器扩展内容脚本已加载');
// 监听来自扩展的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('内容脚本收到消息:', request);
if (request.action === 'highlight') {
// 显示一个临时的通知
showNotification(request.message || '操作已执行');
sendResponse({ success: true });
}
return true;
});
// 在页面上显示通知
function showNotification(message) {
// 检查是否已存在通知元素
let notification = document.getElementById('extension-notification');
if (!notification) {
notification = document.createElement('div');
notification.id = 'extension-notification';
document.body.appendChild(notification);
}
notification.textContent = message;
notification.classList.add('show');
// 3秒后隐藏
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
}
// 可选:添加快捷键监听
document.addEventListener('keydown', (e) => {
// Ctrl + Shift + E 触发扩展功能
if (e.ctrlKey && e.shiftKey && e.key === 'E') {
e.preventDefault();
showNotification('快捷键触发!');
// 向后台脚本发送消息
chrome.runtime.sendMessage({
action: 'getData'
}, (response) => {
console.log('后台响应:', response);
});
}
});