is it possible to create chrome & edge extension code manifest v3 to detect when internet connection is offline when offline show message notify user and sound alarm and then show duration of offline and then show count of time it offline in extension icon this count will reset when enter new day ,explain what you understand and show me code for this.
Assistant
Understanding Your Request:
You want to create a Chrome and Edge browser extension (Manifest V3) that performs the following functions:
Detects when the internet connection goes offline.
When offline:
Shows a notification message to the user.
Plays a sound alarm.
Tracks and displays the duration of the offline period.
Increments a counter each time the connection goes offline.
Displays the count of offline occurrences on the extension icon badge.
Resets the offline count daily.
Implementation Overview:
Background Script (service_worker): Runs in the background to monitor network connectivity changes.
Alarm API: Used to schedule events (e.g., reset the offline count daily).
Notifications API: Displays notifications to the user.
Badge API: Updates the extension icon with the offline count.
Storage API: Stores the offline count and timestamps.
Web Audio API: Plays a sound when the connection goes offline.
Sample Code:
Let's proceed to create the necessary files for the extension.
1. manifest.json
json
{
"manifest_version": 3,
"name": "Offline Detector",
"version": "1.0",
"description": "Detects when internet connection is offline and notifies the user.",
"permissions": [
"notifications",
"alarms",
"storage"
],
"background": {
"service_worker": "background.js"
},
"icons": {
"16": "icons/16.png",
"32": "icons/32.png",
"48": "icons/48.png",
"128": "icons/128.png"
},
"action": {
"default_title": "Offline Detector"
}
}
Explanation:
Specifies permissions needed.
Defines the background script (service worker).
Sets up the extension icon and action.
2. background.js
javascript
let offlineCount = 0;
let offlineStartTime = null;
// Initialize offline count and set alarm for daily reset
chrome.runtime.onInstalled.addListener(() => {
// Set or reset the offline count at installation
chrome.storage.local.set({ offlineCount: 0 });
// Clear existing alarms and set a new one for midnight
chrome.alarms.clearAll(() => {
setDailyResetAlarm();
});
});
// Set an alarm for midnight to reset offline count
function setDailyResetAlarm() {
const now = new Date();
const midnight = new Date();
midnight.setHours(24, 0, 0, 0); // Next midnight
const delay = midnight.getTime() - now.getTime();
chrome.alarms.create('resetOfflineCount', { when: Date.now() + delay });
}
// Listener for the alarm
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'resetOfflineCount') {
chrome.storage.local.set({ offlineCount: 0 }, () => {
updateBadge(0);
});
setDailyResetAlarm(); // Schedule next reset
}
});
// Monitor network connectivity changes
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
function handleOnline() {
if (offlineStartTime) {
const offlineDuration = Date.now() - offlineStartTime;
offlineStartTime = null;
// Show notification with offline duration
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/128.png',
title: 'Back Online',
message: `Connection was offline for ${formatDuration(offlineDuration)}.`,
priority: 2
});
}
}
function handleOffline() {
offlineStartTime = Date.now();
// Increment offline count
chrome.storage.local.get('offlineCount', (data) => {
offlineCount = data.offlineCount + 1;
chrome.storage.local.set({ offlineCount: offlineCount }, () => {
updateBadge(offlineCount);
});
});
// Show notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/128.png',
title: 'Connection Lost',
message: 'Your internet connection is offline.',
priority: 2
});
// Play sound
playAlertSound();
}
// Update the badge text with the offline count
function updateBadge(count) {
chrome.action.setBadgeText({ text: count > 0 ? count.toString() : '' });
chrome.action.setBadgeBackgroundColor({ color: '#FF0000' });
}
// Play an alert sound
function playAlertSound() {
const audio = new Audio(chrome.runtime.getURL('alert.mp3'));
audio.play();
}
// Helper to format duration in HH:MM:SS
function formatDuration(ms) {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
const minutes = Math.floor((totalSeconds % 3600) / 60)
.toString()
.padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
return `${hours}:${minutes}:${seconds}`;
}
Explanation:
Uses event listeners for online and offline events to detect connectivity changes.
When offline:
Records the start time.
Increments the offline count and updates the badge.
Shows a notification.
Plays a sound.
When back online:
Calculates the offline duration.
Shows a notification with the duration.
Sets up an alarm to reset the offline count at midnight.
Stores the offline count using chrome.storage.local.
updateBadge updates the extension icon badge with the current offline count.
playAlertSound plays a sound using the Web Audio API.
3. Sound File
Include a sound file named alert.mp3 in your extension directory.
Note: Ensure you have the rights to use the sound file you include.
4. Icons
Include icon files in the icons directory as specified in manifest.json (sizes 16x16, 32x32, 48x48, 128x128).
5. Permissions Explanation
In your extension's listing (if you publish it), you should justify the permissions:
Notifications: To display notifications when the connection goes offline or comes back online.
Alarms: To reset the offline count daily.
Storage: To store the offline count persistently.
Additional Considerations:
Edge Compatibility: Since Edge is Chromium-based, the extension should work seamlessly in Edge as well.
Service Worker Context: Manifest V3 uses service workers instead of background pages. Note that certain Web APIs like window may not be available. To detect online/offline status in a service worker, you may need to rely on intermittent network checks rather than event listeners.
Revised background.js for Manifest V3 Service Worker
Manifest V3 service workers do not have access to the window object. Instead, we can use periodic network checks.
javascript
Explanation:
Since service workers don't have access to window, we can't use window.addEventListener('online', ...).