browser-plugin-creator
Version:
A modern scaffolding tool for creating browser extensions with ease
63 lines (54 loc) • 1.63 kB
JavaScript
// 后台服务工作线程
chrome.runtime.onInstalled.addListener(() => {
console.log('{{name}} 侧边栏扩展已安装');
// 设置默认存储
chrome.storage.sync.set({
settings: {
autoRefresh: true,
refreshInterval: 5000,
theme: 'light'
}
});
});
// 监听标签页变化
chrome.tabs.onActivated.addListener((activeInfo) => {
console.log('切换到标签页:', activeInfo.tabId);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
console.log('页面加载完成:', tab.url);
}
});
// 监听来自内容脚本的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.type) {
case 'GET_TAB_INFO':
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
sendResponse({
tabId: tabs[0].id,
url: tabs[0].url,
title: tabs[0].title
});
});
return true;
case 'OPEN_SIDE_PANEL':
chrome.sidePanel.open({ windowId: chrome.windows.WINDOW_ID_CURRENT });
break;
}
});
// 设置上下文菜单
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'open-side-panel',
title: '打开{{name}}侧边栏',
contexts: ['page']
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'open-side-panel') {
chrome.sidePanel.open({ tabId: tab.id });
}
});
// 配置侧边栏
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
console.log('{{name}} 后台服务工作线程已启动');