Files
emoji-chrome-extension/background.js
2025-09-06 23:58:42 +07:00

48 lines
2.0 KiB
JavaScript

// Let Chrome open the panel when the toolbar icon is clicked
// Guard: some Chromium variants may not expose sidePanel
const hasSidePanel = !!chrome.sidePanel?.setOptions;
chrome.runtime.onInstalled.addListener(() => {
if (hasSidePanel) chrome.sidePanel.setPanelBehavior?.({ openPanelOnActionClick: true });
});
// If you still want to ensure the correct path on click, setOptions ONLY:
chrome.action.onClicked.addListener(async () => {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id) return;
// inject content.js before the panel opens (best effort; ignore errors)
try {
const pong = await chrome.tabs.sendMessage(tab.id, { type: 'dewemoji_ping' });
if (!pong?.ok) {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
}
} catch {
// No content script: inject it
try { await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }); } catch {}
}
await chrome.sidePanel.setOptions({ tabId: tab.id, path: "panel.html" });
try { await chrome.sidePanel.open({ tabId: tab.id }); } catch {}
});
// Keyboard shortcut: we do open() here (this is a user gesture)
chrome.commands.onCommand.addListener(async (command) => {
if (command !== "toggle-panel") return;
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (!tab?.id) return;
// inject content.js before we open the panel with keyboard
try {
const pong = await chrome.tabs.sendMessage(tab.id, { type: 'dewemoji_ping' });
if (!pong?.ok) {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] });
}
} catch {
// No content script: inject it
try { await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }); } catch {}
}
await chrome.sidePanel.setOptions({ tabId: tab.id, path: "panel.html" });
await chrome.sidePanel.open({ tabId: tab.id });
});