MOOC Utils

Utils like auto assignment solver extension and course notice announcment notification for MOOC courses

Background service

Introduction#

The background service worker owns initialization, dependency wiring, platform adapters, the message router, handlers, and lifecycle hooks like icon click and side panel open. If you need to extend or debug background work, start here.

Project structure#

The background service worker is organized around a dependency injection pattern. Platform adapters abstract browser APIs, services encapsulate business logic, and handlers implement message-specific workflows. The router centralizes message dispatching.

Core components#

  • Initialization and DI: The background entry point initializes logging, platform adapters, services, and message handlers, then registers the router with the runtime adapter.
  • Message Router: Central dispatcher that selects a handler by message type, sends responses for both sync and async handlers.
  • Platform Adapters: Unified wrappers for browser APIs (runtime, tabs, scripting, panel) enabling cross-browser compatibility.
  • Services: Business logic abstractions (e.g., Gemini API client, storage).
  • Handlers: Message-specific implementations for extraction, screenshot capture, Gemini requests, answer application, and page info retrieval.

Architecture overview#

The background worker listens for messages, routes them to handlers, and coordinates with platform adapters and services. Handlers may interact with content scripts via tabs messaging or call services directly.

Detailed component analysis#

Service worker initialization and dependency injection#

  • Logger creation with contextual prefix.
  • Platform adapters created via factories for runtime, tabs, scripting, and panel.
  • Services created with adapters injected (e.g., Gemini service with runtime adapter).
  • Handlers created with adapters/services injected.
  • Router instantiated with handlers and logger, registered with runtime adapter.
  • Extension icon click listener opens the panel via panel adapter.
  • Panel behavior configured for Chrome.

Message router implementation#

  • Selects handler by message.type.
  • Ensures sendResponse is always called.
  • Handles both synchronous and asynchronous handlers.
  • Returns true synchronously for Firefox compatibility.
  • Logs errors and keeps response on exceptions.

Message types and retry utilities#

  • MESSAGE_TYPES enumerates all supported message types for UI and background communication.
  • sendMessageWithRetry adds reliability for transient connection failures, particularly important for Firefox.

Extraction handler#

Responsibilities:

  • Resolve target tab (provided or active).
  • Ensure content script is loaded by pinging and injecting if needed.
  • Request page HTML from content script.
  • Return tab/window metadata along with extraction result.

Screenshot capture handler#

Responsibilities:

  • Accepts tabId and windowId.
  • Delegates to screenshot service to capture full-page screenshots.
  • Returns array of screenshot objects with metadata.

Screenshot service#

Responsibilities:

  • Compute page dimensions via content script.
  • Scroll in viewport-sized increments.
  • Capture visible tab for each viewport.
  • Restore original scroll position.
  • Return array of screenshot objects.

Gemini handler#

Responsibilities:

  • Receive apiKey, payload, model from message.
  • Call service’s directAPICall to avoid Firefox message channel timeouts.
  • Return parsed response or error.

Answer application handler#

Responsibilities:

  • Resolve target tab (provided or active).
  • Ensure content script is loaded by pinging and injecting if needed.
  • Forward the original message (APPLY_ANSWERS or SUBMIT_ASSIGNMENT) to the content script.
  • Return response or error.

Page info handler#

Responsibilities:

  • Determine if current tab is an assignment page (NPTEL/SWAYAM assessment/assignment/quiz).
  • Ensure content script is loaded if needed.
  • Request page info from content script and return structured metadata.

Extension lifecycle management and panel opening#

  • Icon click listener: On action icon click, opens the panel for the clicked tab.
  • Panel behavior: Configures Chrome to open the side panel on action click.
  • Cross-browser panel handling: Uses panel adapter to abstract Chrome sidePanel vs Firefox sidebarAction.

Dependency analysis#

The background worker composes a connected dependency graph:

  • index.js orchestrates DI and wiring.
  • router.js depends on MESSAGE_TYPES.
  • Handlers depend on platform adapters and services.
  • Services depend on adapters and core utilities.
  • Platform adapters depend on browser polyfill.

Performance considerations#

  • Asynchronous message handling: The router keeps channels open for async handlers to prevent Firefox-specific issues.
  • Screenshot capture throttling: Limits to a maximum number of screenshots to avoid API rate limits and reduce processing overhead.
  • Content script injection delays: Includes deliberate waits for Firefox initialization to improve reliability.
  • Retry logic: sendMessageWithRetry mitigates transient connection failures during background initialization.

Troubleshooting guide#

Common issues and resolutions:

  • Content script not responding: Handlers inject content script and verify with a ping; ensure the content script is compatible and reload the page if needed.
  • No active tab found: Handlers return explicit errors when no active tab is available; switch to a valid tab.
  • Panel open/close failures: Panel adapter logs and throws on unavailable APIs; verify browser support for sidePanel or sidebarAction.
  • Gemini API errors: Gemini service parses raw responses and throws on parse failures; check API key validity and payload schema.
  • Router errors: Router logs handler errors and still calls sendResponse; inspect logs for details.

Conclusion#

The worker is a thin composition root: adapters in, router out, handlers as pure-ish functions of those deps.