import 'dart:html' as html; import '../models/tab_data.dart'; // communication with browser extension // Listens for messages // callbacks to notify UI // start/stop tracking // Converts extension class ExtensionService { Function(List)? onTabsUpdate; Function()? onTrackingStart; Function()? onTrackingStop; void setupListener() { html.window.onMessage.listen((event) { final data = event.data; if (data is Map && data['source'] == 'tab-tracker-extension') { _handleExtensionMessage(Map.from(data)); } }); } void _handleExtensionMessage(Map data) { print('Received from extension: $data'); if (data['action'] == 'updateTabs') { final extensionTabs = (data['tabs'] as List).map((tab) { tab['type'] = 'tab'; return TabData.fromJson(tab); }).toList(); onTabsUpdate?.call(extensionTabs); } else if (data['action'] == 'clear') { onTrackingStop?.call(); } else if (data['response'] != null) { final response = data['response']; if (response['status'] == 'started') { onTrackingStart?.call(); } else if (response['status'] == 'stopped') { onTrackingStop?.call(); } } } void sendMessage(Map message) { html.window.postMessage({ 'source': 'tab-tracker-webapp', ...message }, '*'); } void startTracking() { sendMessage({'action': 'startTracking'}); } void stopTracking() { sendMessage({'action': 'stopTracking'}); } void getStatus() { sendMessage({'action': 'getStatus'}); } } // Handles communication, browser extension for live tab tracking. // // Callback triggered when extension updates. // // SetupListener listens for messages from browser extension through window.postMessage. // // Messages arrive, filters only process ones from specific extension. // // _handleExtensionMessage processes different types of messages, tab updates, tracking status changes. // // SendMessage method sends commands back to the extension with a source identifier. // // startTracking, stopTracking, getStatus interface to control extension // callback allows UI to react immediately when data arrives.