Browser-Tab-Manager/lib/services/extension_service.dart

80 lines
2.4 KiB
Dart
Raw Normal View History

import 'dart:html' as html;
import '../models/tab_data.dart';
class ExtensionService {
Function(List<TabData>)? 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<String, dynamic>.from(data));
}
});
}
void _handleExtensionMessage(Map<String, dynamic> 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<String, dynamic> message) {
html.window.postMessage({
'source': 'tab-tracker-webapp',
...message
}, '*');
}
void startTracking() {
sendMessage({'action': 'startTracking'});
}
void stopTracking() {
sendMessage({'action': 'stopTracking'});
}
void getStatus() {
sendMessage({'action': 'getStatus'});
}
}
// This service handles real-time communication with the browser extension for live tab tracking.
//
// It uses callback functions that get triggered when the extension sends updates.
//
// The setupListener method listens for messages from the browser extension through window.postMessage.
//
// When messages arrive, it filters them to only process ones from our specific extension.
//
// The _handleExtensionMessage method processes different types of messages like tab updates and tracking status changes.
//
// It converts raw tab data from the extension into our TabData objects.
//
// The sendMessage method sends commands back to the extension with a source identifier.
//
// Methods like startTracking, stopTracking, and getStatus provide a clean interface to control the extension.
//
// This enables our app to show live updates as users open and close tabs in their browser.
//
// The callback pattern allows the UI to react immediately when extension data arrives.