Skip to content

Commit

Permalink
Web notifications base
Browse files Browse the repository at this point in the history
  • Loading branch information
hmziqrs committed Nov 18, 2024
1 parent f375fad commit 4bc22d0
Show file tree
Hide file tree
Showing 5 changed files with 159 additions and 34 deletions.
5 changes: 3 additions & 2 deletions lib/main.web.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
Expand All @@ -16,13 +17,13 @@ Future<void> main() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await AppFCM.init();

App.showAds = false;
AppFCM.init();


await Hive.initFlutter();
await Hive.openBox('app');
UIUtils.setLightStatusBar();

final List<NavigatorObserver> observers = [
FirebaseAnalyticsObserver(
Expand Down
9 changes: 9 additions & 0 deletions lib/services/notification/local.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class LocalNotification {
android: AndroidInitializationSettings(
'@drawable/ic_notification',
),

// iOS: DarwinInitializationSettings(
// onDidReceiveLocalNotification:
// LocalNotification.onDidReceiveLocalNotification,
Expand All @@ -20,6 +21,13 @@ class LocalNotification {

LocalNotification.ins.initialize(
initializationSettings,
onDidReceiveBackgroundNotificationResponse: (details) {
print("onDidReceiveBackgroundNotificationResponse, $details");
},
onDidReceiveNotificationResponse: (response) {
print("onDidReceiveNotificationResponse $response");
},

// onSelectNotification: (string) {
// return LocalNotification.handleNotificationAction(
// string != null && string != '' ? jsonDecode(string) : {},
Expand Down Expand Up @@ -51,6 +59,7 @@ class LocalNotification {

static Future<void> showNotification(RemoteMessage message) async {
final notification = message.notification;
print("showNotification: ${notification?.title} ${notification?.body}");
if (notification == null) return;
await LocalNotification.ins.show(
notification.hashCode,
Expand Down
12 changes: 11 additions & 1 deletion lib/services/notification/notification.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import 'dart:io';
import 'dart:convert';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
// import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

part 'background.dart';
part 'local.dart';
Expand All @@ -25,13 +26,21 @@ class AppFCM {
badge: true,
sound: true,
);

onReceiveRemoteMessage();
}

static Future<String?> getToken() async {
if (kIsWeb) {
const vapidKey =
"BEsAR1WvAgQea8790PJxv9DWM2DLzPwyruTXY6B8GAKH6vfUZ2jTLBvqSksc9tXgSnsxvoXTXbACbpft08FKcd8";
return AppFCM.ins.getToken(vapidKey: vapidKey);
}
return AppFCM.ins.getToken();
}

static void onReceiveRemoteMessage() async {
print("MESGSGE");
// _terminatedState();
_foregroundState();
_backgroundState();
Expand Down Expand Up @@ -70,6 +79,7 @@ class AppFCM {
provisional: false,
sound: true,
);
print(settings.authorizationStatus);

return settings;
}
Expand Down
81 changes: 81 additions & 0 deletions web/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Please see this file for the latest firebase-js-sdk version:
// https://github.com/firebase/flutterfire/blob/master/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart
console.log('[firebase-messaging-sw.js] Start loading...');
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js");
// importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js');
// importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js');


console.log('[firebase-messaging-sw.js] Imported scripts!');

firebase.initializeApp({
apiKey: "AIzaSyAYQ0EZXBNVtoTNlkTQgUs7sOUYtdeTdGA",
authDomain: "flutter-ui-challenges-hgl.firebaseapp.com",
databaseURL: "https://flutter-ui-challenges-hgl.firebaseio.com",
projectId: "flutter-ui-challenges-hgl",
storageBucket: "flutter-ui-challenges-hgl.appspot.com",
messagingSenderId: "322047224635",
appId: "1:322047224635:web:16d105e8b9b35a62d2e51e",
measurementId: "G-HS61TMQ4DZ"
});

console.log('[firebase-messaging-sw.js] Firebase initialized!');

// Necessary to receive background messages:
const messaging = firebase.messaging();
console.log('[firebase-messaging-sw.js] Messaging initialized!');

const isSupported = firebase.messaging.isSupported();
console.log('[firebase-messaging-sw.js] isSupported: ', isSupported);

messaging.onMessage = ((payload) => {
console.log('[firebase-messaging-sw.js] Received foreground message ', payload);

const notificationOptions = {
body: payload.notification.body,
icon: '/icons/Icon-192.png',
badge: '/icons/Icon-192.png',
tag: payload.notification.tag,
data: payload.data
};

return self.registration.showNotification(
payload.notification.title,
notificationOptions
);
});

// Optional:
messaging.onBackgroundMessage((payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);

const notificationOptions = {
body: payload.notification.body,
icon: '/icons/Icon-192.png',
badge: '/icons/Icon-192.png',
tag: payload.notification.tag,
data: payload.data
};

return self.registration.showNotification(
payload.notification.title,
notificationOptions
);
});

// Handle notification clicks
self.addEventListener('notificationclick', (event) => {
console.log('[firebase-messaging-sw.js] Notification click: ', event);
event.notification.close();

// Add custom click handling here
const urlToOpen = event.notification.data?.url || '/';

event.waitUntil(
clients.openWindow(urlToOpen)
);
});


// messaging.
86 changes: 55 additions & 31 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<!DOCTYPE html><html><head>
<!--
<!DOCTYPE html>
<html>

<head>
<!--
If you are serving your web app in a path other than the root, change the
href value below to reflect the base path you are serving from.
Expand All @@ -12,24 +15,24 @@
This is a placeholder for base href that will be replaced by the value of
the `--base-href` argument provided to `flutter build`.
-->
<base href="$FLUTTER_BASE_HREF">
<base href="$FLUTTER_BASE_HREF">

<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">

<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="flutter_uis">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="flutter_uis">
<link rel="apple-touch-icon" href="icons/Icon-192.png">

<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png">

<title>flutter_uis</title>
<meta name="description" content="A new Flutter project.">
<link rel="manifest" href="manifest.json">
<style id="splash-screen-style">
<title>flutter_uis</title>
<meta name="description" content="A new Flutter project.">
<link rel="manifest" href="manifest.json">
<style id="splash-screen-style">
html {
height: 100%
}
Expand All @@ -38,7 +41,7 @@
margin: 0;
min-height: 100%;
background-color: #ffffff;
background-size: 100% 100%;
background-size: 100% 100%;
}

.center {
Expand All @@ -51,19 +54,22 @@
}

.contain {
display:block;
width:100%; height:100%;
display: block;
width: 100%;
height: 100%;
object-fit: contain;
}

.stretch {
display:block;
width:100%; height:100%;
display: block;
width: 100%;
height: 100%;
}

.cover {
display:block;
width:100%; height:100%;
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}

Expand All @@ -90,7 +96,7 @@
@media (prefers-color-scheme: dark) {
body {
background-color: #000000;
}
}
}
</style>
<script id="splash-screen-script">
Expand All @@ -102,13 +108,31 @@
</script>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
</head>
<body>

<body>
<picture id="splash">
<source srcset="splash/img/light-1x.png 1x, splash/img/light-2x.png 2x, splash/img/light-3x.png 3x, splash/img/light-4x.png 4x" media="(prefers-color-scheme: light)">
<source srcset="splash/img/dark-1x.png 1x, splash/img/dark-2x.png 2x, splash/img/dark-3x.png 3x, splash/img/dark-4x.png 4x" media="(prefers-color-scheme: dark)">
<img class="center" aria-hidden="true" src="splash/img/light-1x.png" alt="">
<source
srcset="splash/img/light-1x.png 1x, splash/img/light-2x.png 2x, splash/img/light-3x.png 3x, splash/img/light-4x.png 4x"
media="(prefers-color-scheme: light)">
<source
srcset="splash/img/dark-1x.png 1x, splash/img/dark-2x.png 2x, splash/img/dark-3x.png 3x, splash/img/dark-4x.png 4x"
media="(prefers-color-scheme: dark)">
<img class="center" aria-hidden="true" src="splash/img/light-1x.png" alt="">
</picture>
<script src="flutter_bootstrap.js" async=""></script>

<script src="flutter_bootstrap.js" async=""></script>
<script>
console.log('Loading flutter...');
if ('serviceWorker' in navigator) {
console.log('Registering service worker...');
window.addEventListener('load', function () {
console.log('Service worker loaded...');
let scope = { scope: '/firebase-cloud-messaging-push-scope' };
navigator.serviceWorker.register('firebase-messaging-sw.js', scope);
// });
});
}
</script>

</body>

</body></html>
</html>

0 comments on commit 4bc22d0

Please sign in to comment.