How to request notification permission again on web through flutter - firebase

I have integrated notifications for flutter web, its working fine when i give permission for the first time, but lets say user has denied it so is there any way to request notifications permission again to get token in dart files from javascript files ?
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: 'favicon.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});

You can follow a similar permission call posted as an Answer in this post. For your use case, you'll need to use push permission since Firebase Cloud Messaging for web needs Push API support as mentioned in the official docs
Use dart:html package for the permission requests using Web API. Import the dart:html package, and set a prefix. In this sample, we used 'html'
import 'dart:html' as html;
Create a helper method to check for push permissions.
checkPushPermission() async {
var pushPermission = await html.window.navigator.permissions.query({"name": "push"});
print('push permission: ${pushPermission.state}')
}
Call checkPushPermission() to verify the current push permission state, and it should display the relevant permission dialog.
checkPushPermission();
Be reminded that FlutterFire Cloud Messaging is yet to be fully supported for Web, and there could be quirks in its current state. Also, be aware of Web API's browser compatibility.

I did not test it myself but it seems you should call the browser "requestPermission" API:
https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API
For Flutter I have seen there is this call in "dart:html" package:
https://api.flutter.dev/flutter/dart-html/Notification/requestPermission.html

Related

WebConfig doesn't return measurementId

I am trying to enable firebase analytics in my existing firebase project. The project is a static React website that only uses Firebase hosting.
Following this get start tutorial, I am getting the following error in my console:
Ignored "config" command. Invalid arguments found
Searching how to solve this problem, I found this comment and checked that my webConfig get request is not returning the measurementId. However I couldn't find any info about how to correct it.
//firebase.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics} from "firebase/analytics";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "{ApiKey}",
authDomain: "{projectId}.firebaseapp.com",
projectId: "{projectId}",
storageBucket: "{projectId}.appspot.com",
messagingSenderId: "{messagingSenderId}",
appId: "{appId}",
measurementId: "{measurementId}",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
WebConfig call (Http 200, Get):
response:
{
"projectId": "{projectId}",
"appId": "{appId}",
"storageBucket": "{projectId}.appspot.com",
"authDomain": "{projectId}.firebaseapp.com",
"messagingSenderId": "{messagingSenderId}"
}
Is there any config that I am missing? what should I do to make it work?
There could be something wrong with the stream for your web app that’s why the measurementId is not being configured. You could try to unlink and relink to your Google Analytics integration which usually resolves any broken integration. Make sure that the currently linked GA property is the one you’re going to use for relinking to avoid losing your data.

Firebase App Check with Vue 3 Invalid app resource name

I am trying to get Firebase App Check working in a Vue 3 web app. I have Firebase configured and reCAPTCHA v3 configured.
Here is the code where I initialize Firebase and App Check. I am logging the recaptcha site key to console to make sure the env variables are getting injected correctly.
const fbConfig = {
apiKey: import.meta.env.VITE_APP_FIREBASE_APIKEY,
authDomain: import.meta.env.VITE_APP_FIREBASE_AUTHDOMAIN,
projectId: import.meta.env.VITE_APP_FIREBASE_PROJECTID,
appId: import.meta.env.VITE_APP_FIREBASE_APPID,
storageBucket: import.meta.env.VITE_APP_STORAGEBUCKET,
messagingSenderId: import.meta.env.VITE_APP_MESSAGINGSENDERID,
}
const fbapp = initializeApp(fbConfig)
if (location.hostname === "localhost") {
self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;
}
console.log("APPCHECK Token: ", import.meta.env.VITE_APP_RECAPTCHA_SITEKEY)
const appCheck = initializeAppCheck(fbapp, {
provider: new ReCaptchaV3Provider(import.meta.env.VITE_APP_RECAPTCHA_SITEKEY),
// Optional argument. If true, the SDK automatically refreshes App Check
// tokens as needed.
isTokenAutoRefreshEnabled: true
});
This works as expected on local host where the debug token is used. When I deploy to a live site I get this error.
{ code: 400, message: "Invalid app resource name: \"projects/<name removed>/apps/\"<code removed>\"\".", status: "INVALID_ARGUMENT" }
Any thoughts?
Found the problem. The appId was getting quoted in the environment variables for some reason. Fixing that fixed the issue.

Having issues getting Firebase (Web version 9) push notifications working in Unity WebGL build

I'm trying to get push notifications working with the Web version 9 JavaScript Firebase SDK in a Unity WebGL build. I got Firebase integrated and was successfully retrieving a token from Firebase when calling getToken(), but when I add the firebase-messaging-sw.js file, I start getting this error message:
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:52559/firebase-cloud-messaging-push-scope') with script ('http://localhost:52559/firebase-messaging-sw.js'): ServiceWorker script evaluation failed (messaging/failed-service-worker-registration).
I've webpacked the firebase-messaging-sw.js (which the instructions in Firebase don't explicitly call out, but I'm assuming you have to do this to get it to work since I had to do the same thing for the rest of the firebase code and it's the whole point of version 9). I placed the webpacked firebase-messaging-sw.js file in the same folder as my index.html file.
Here's the firebase-messaging-sw.js file contents prior to packing:
import { getMessaging } from "firebase/messaging";
import { onBackgroundMessage } from "firebase/messaging/sw";
const firebaseConfig = {
apiKey: "XXXXXX",
authDomain: "XXXXXX",
databaseURL: "XXXXXX",
projectId: "XXXXXX",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXX",
appId: "XXXXXX",
measurementId: "XXXXXX"
};
firebase.initializeApp(firebaseConfig);
const messaging = getMessaging();
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I'm seeing the same results when I build and run locally and when I run it on a remote host. Has anyone got this to work or have any idea what I'm doing wrong?

Getting issue in generating Firebase token in React JS application

importScripts("https://www.gstatic.com/firebasejs/9.8.3/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.8.3/firebase-messaging-compat.js");
// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
apiKey: "AIzaSyDk4dYeydr4q3npWx4iqKWejq33r1E",
authDomain: "tengage-33e12.fireeapp.com",
projectId: "tengage-33e12",
storageBucket: "tengage-33e12.appspot.com",
messagingSenderId: "1076165210",
appId: "1:1076165210:web:c9560924940a068ce3",
measurementId: "G-5FMCR8M0G8",
};
firebase.initializeApp(firebaseConfig);
// Retrieve firebase messaging
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log(" message ", payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
I have one React js project in which I have to integrate the FCM.
I have added firebase-messaging-sw.js in public folder.
and added the firebbase dependency also.
when I am trying to get token i am getting the error.
SecurityError: Failed to register a ServiceWorker for scope ('http://localhost:3005/') with script ('http://localhost:3005/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html').
But with the same firebase credentials when I tried to get the token in the newly created application its giving the token.
The error that is mentioned may occur due to a few reasons , one of which could be an error in the design pattern or syntax. However, it means that any requests for unknown text files initially get redirected to index.html, and therefore return with the MIME type of "text/html", even if it's actually a JavaScript or SVG or some other kind of plaintext file.
Refer below for example:
// Load React App
// Serve HTML file for production
if (env.name === "production") {
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public""index.html"));
});
}
You may try to add a specific route for service-worker.js before the wildcard route:
app.get("/service-worker.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "public", "service-worker.js"));
});
app.get("*", function response(req, res) {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
Now, when the browser looks for service-worker.js, it will return it with the correct MIME type.
(Note that if you try adding the service-worker.js route after the wildcard, it won't work because the wildcard route will override.)
You also may want to check if the URL http://localhost:3005/firebase-messaging-sw.js, is getting served and its MIME type from the browser interface.
Also , please make sure that the service worker file is generated (Chrome DevTools -> Sources -> Filesystem). You may receive such an error if the above example service-worker.js file is not generated at all (check your deployment script).
You may also refer the links below for more insight:
[1] : https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token
[2] : https://firebase.google.com/docs/cloud-messaging/server
[3] : FCM getToken() Failed to register a ServiceWorker for scope error Flutter web

Firebase Google Auth in Electron App gives "location.protocol" must be http, https

<button id="signin_with_google_button">sign in</button>
<script>
var firebase = require("firebase");
var config = {
apiKey: "AIzaSyAwp7hhcZGyNfZOY8AOeIrpzkzL69quiS0",
authDomain: "https://sdsdss-efefx22.firebaseapp.com",
databaseURL: "https://sdsdss-efefx22.firebaseio.com",
projectId: "sdsdss-efefx22",
storageBucket: "sdsdss-efefx22.appspot.com",
messagingSenderId: "3232323"
};
firebase.initializeApp(config);
var provider = new firebase.auth.GoogleAuthProvider();
document.querySelector('#signin_with_google_button')
.addEventListener('click', () => {
firebase.auth().signInWithPopup(provider).then(function(result){
console.log("Google result", result);
}).catch(function(error) {
console.log("Google Error", error);
});
});
</script>
This operation is not supported in the environment this application is
running on. "location.protocol" must be http, https or
chrome-extension and web storage must be enabled.
https://firebase.google.com/docs/auth/web/google-signin
firebase version:
"firebase": "4.6.2",
PS: I have gone through location.protocol" must be http or https
but no one seems to suggest any work around for electron.
Update:
Tried implicit email auth, it works as suggested here
But firebaseui still doesn't work as electron in not officially supported, explained here . Even though it is not officially supported but I am sure there will be workarounds, keeping the question open for people to suggest workarounds.

Resources