Panduan Full Stack Engineer: Komunikasi IPC Aman antara Content Script & Service Worker di Ekstensi Chrome Manifest V3

Spesialisasi Rekayasa Perangkat Lunak: Ditulis oleh Aldian Fazrihady — Senior Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend Engineer, AI Application Engineer & Full Stack Engineer.

1. Model Isolasi Proses pada Ekstensi Browser Chrome Manifest V3

Dalam arsitektur Chrome Extensions Manifest V3, kode berjalan di tiga konteks keamanan yang terpisah: skrip halaman web (Main World), Content Scripts (Isolated World), dan Background Service Worker yang bersifat sementara (ephemeral). Sebagai Full Stack Engineer, merancang jalur komunikasi antar-proses (IPC) yang aman wajib memvalidasi sender.id dan sender.url agar halaman web berbahaya tidak dapat menyalahgunakan hak akses ekstensi.

2. Pola Router Pesan Asinkron & Penanganan Siklus Hidup Service Worker

Perhatikan bahwa listener chrome.runtime.onMessage di Manifest V3 wajib mengembalikan true secara sinkron ketika menangani Promise asinkron agar saluran respons tidak tertutup sebelum selesai. Berikut adalah implementasi lengkap IPC Manifest V3:

// content_script.js
function sendCurationPayload() {
    const payload = {
        message: "initiate_curation",
        url: window.location.href,
        title: document.title,
        selected_text: window.getSelection ? window.getSelection().toString() : ""
    };

    console.log("[content_script.js] Sending payload to broker:", payload);
    
    // Send to background service worker
    chrome.runtime.sendMessage(payload, function(response) {
        if (chrome.runtime.lastError) {
            console.error("Broker connection failed:", chrome.runtime.lastError.message);
            return;
        }
        console.log("[content_script.js] Received response from broker:", response);
    });
}
// background.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log("[background.js] Incoming message intercepted:", message);

    if (message.message === "initiate_curation") {
        // Execute an async API request to store the curation data
        storeCurationRecord(message)
            .then(data => {
                // Send success response back to content script
                sendResponse({ status: "success", data: data });
            })
            .catch(error => {
                sendResponse({ status: "error", error: error.message });
            });
            
        return true; // Keep connection open for async sendResponse callback!
    }

    if (message.message === "open_new_tab") {
        chrome.tabs.create({ url: message.url });
        sendResponse({ status: "tab_opened" });
    }
});

async function storeCurationRecord(payload) {
    const response = await fetch("https://api.yourportal.com/curate/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
    });
    return response.json();
}

Ringkasan Arsitektur Produksi & Praktik Terbaik (Checklist Teknis)


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 15+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs