// Sluša poruke iz popupa
browser.runtime.onMessage.addListener(async msg => {
if (msg.action !== 'insertTemplate') return;
try {
// 1. Nađi aktivni Compose tab
const [tab] = await browser.tabs.query({
active: true,
currentWindow: true,
windowType: 'messageCompose',
});
if (!tab) throw new Error('Nije pronađen Compose tab');
// 2. Dohvati postojeći sadržaj
const details = await browser.compose.getComposeDetails(tab.id);
// 3. Spoji stari i novi tekst
let newBody;
if (details.isPlainText) {
// 1. Grab existing text
const old = details.plainTextBody || '';
// 2. Build new body by prepending with two-line break spacer
// If there's no old content, just use msg.text
newBody = msg.text + (old ? '\n' + old : '');
// 3. Set the updated plain-text body
await browser.compose.setComposeDetails(tab.id, {
plainTextBody: newBody,
});
} else {
const old = details.body || '';
// If content already contains HTML tags, use as-is; otherwise convert newlines
const htmlTpl = msg.text.includes('<') ? msg.text : msg.text.replace(/\n/g, '
');
const bodyTag = '