Flutter Web pass Firebase Auth to HTML - javascript

On a Flutter Web Application, I initialize Firebase in the index.html like below.
<body>
<!-- Check type of device and block all mobile phone devices! Tablets should work -->
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-functions.js"></script>
<script src="init-firebase.js" defer></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js?v=3005614081');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
Further, I have an init-firebase.js for the Firebase config as per below.
// Initialize Firebase
var firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projected: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "..."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
This works all fine and within Dart I can access Firebase Auth, etc.
I wonder however how I can access Firebase Auth when I open a new HTML file within the application like example.html?
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
void initState() {
_showDocument();
super.initState();
}
_showDocument() async {
await ui.platformViewRegistry.registerViewFactory(
'ExamplePage',
(int viewId) => IFrameElement()
..src = 'https://example.com'
..style.border = 'none');
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: HtmlElementView(viewType: 'ExamplePage'),
));
}
}
In the example.html like below I would like to access Firebase data like Auth, Storage, etc for users who have authenticated in the Flutter Web App but I can't. Calling my init-firebase.js would init Firebase again.
<html>
<head>
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<title>Example</title>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-auth.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-firestore.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-storage.js"></script>
<script defer src="https://www.gstatic.com/firebasejs/8.2.0/firebase-functions.js"></script>
<!-- <script src="init-firebase.js" defer></script> -->
</head>
<body>
<div id="my-view" style="height: 95%; width: 100%;" oncontextmenu="return false;"></div>
<script>
// Access Firebase data like AUTH, Storage, Firestore here.....
</script>
</body>
</html>
The Flutter Web App is still on the same tab and index.html and I am only opening another HTML window within that. Any way to pass Firebase down to HTML?

There is no way to pass a FirebaseApp instance (or services taken from that such as the database or auth) between pages. Each web page that loads in a browser is its own instance, and will need to load the Firebase services it uses.

Related

firebase is not defined (using version 9.6.7)

Am I using outdated code? Also, I set the rules of the database so read and write are true. That makes the database changeable from any device. When I try searching on stack overflow, firebase is not defined, I get irrelevant answers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCnfB3Tfu9bo7PyEvhB1ZAPBbit7ZWm9D8",
authDomain: "square-1cdce.firebaseapp.com",
projectId: "square-1cdce",
storageBucket: "square-1cdce.appspot.com",
messagingSenderId: "82191280296",
appId: "1:82191280296:web:45e62faffbb7e8a94cfa9d",
measurementId: "G-NT53HS3WE9"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
<script>
const db = firebase.database()
db.ref("users/").set({
user:"hello"
});
</script>
</body>
</html>
You have to use the getDatabase function you imported here:
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
So, you can do const db = getDatabase(), and access your realtime using that.
Your snippet with the fix:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCnfB3Tfu9bo7PyEvhB1ZAPBbit7ZWm9D8",
authDomain: "square-1cdce.firebaseapp.com",
projectId: "square-1cdce",
storageBucket: "square-1cdce.appspot.com",
messagingSenderId: "82191280296",
appId: "1:82191280296:web:45e62faffbb7e8a94cfa9d",
measurementId: "G-NT53HS3WE9"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getDatabase()
set(ref(db, 'users/'), {
hello: 'world'
});
</script>
</body>
</html>
You probably won't be able to do this inside StackOverflow snippets because it runs in an iFrame
You can also refer to the docs here:
https://firebase.google.com/docs/database/web/read-and-write

SyntaxError: Unexpected identifier when using Firebase

I am just getting started using firebase and I keep getting an error. It says it is on line thirty one. Thanks in advance! I am a beginner to firebase. I am interediate at javascript. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>firebase</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.14.3/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXX"
};
rules_version = '2';
// Grants a user access to a node matching their user ID
service firebase.storage {
match /b/{bucket}/o {
// Files look like: "user/<UID>/path/to/file.txt"
match /user/{userId}/{allPaths=**} {
allow read, write: if request.auth.uid == userId;
}
}
}
</script>
<script>
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
</script>
</body>
</html>

Issue with Authentication on Firebase

I added a sign-in method for Google on my webpage from Firebase and got a redirect to login with Google successfully. The problem is, after logging in I can't see any of the users in Authentication Section of Firebase. Please help.I've been stuck on this for very long.
Here is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<button type="button" id="googlebtn" onclick="GoogleLogin();">Google</button>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.6.2/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyA4SJ-R5AK6YUd4Z1hXXQBH-UGb0pLi8ug",
authDomain: "oshop-c2ca6.firebaseapp.com",
databaseURL: "https://oshop-c2ca6.firebaseio.com",
projectId: "oshop-c2ca6",
storageBucket: "oshop-c2ca6.appspot.com",
messagingSenderId: "1089602124550",
appId: "1:1089602124550:web:4607bbd77cffa950eebc87",
measurementId: "G-64Z9HFJD92"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="google.js" type="text/javascript"></script>
</body>
</html>
google.js file:
function GoogleLogin(){
var provider=new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider).then(function(){
window.location="index.html";
}).catch(function(error){
var errorMessage=error.message;
alert(errorMessage);
})
}

firebase.auth.RecaptchaVerifier is not a constructor error

Trying to add the Firebase script in my html, after initializing Firebase app with firebase.initializeApp(config);.
So then I have this :
<script>
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button',
{
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
});
</script>
Which provides the error :
firebase.auth.RecaptchaVerifier is not a constructor error
How to solve this error (found similar questions without a direct answer)
How to proceed from here with the full flow ?
EDIT:
I have this in the beginning of the html :
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
I am initializing the app with :
<script>
var config = {
apiKey: "AIzaSxxxxxxxxxxxxxxxZQ14",
authDomain: "xxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxx.firebaseio.com",
projectId: "xxxxxx",
storageBucket: "xxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxx"
};
firebase.initializeApp(config);
const db = firebase.firestore();
db.settings({timestampsInSnapshots:true});
</script>
and those are the only things relate to Firebase I have in this file.
Solved by changing version of the imported files with : (thanks a lot Frank)
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-functions.js"></script>

Firebase initial code

Where do I put the firebase initial code that is responsable to give the keys? Before the html tag closes? or before the body tag closes?
Here is the code:
<script src="https://www.gstatic.com/firebasejs/4.7.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "jsdfiojsifjsiodfjiosfiosdfsj",
authDomain: "dribbbleapi.firebaseapp.com",
databaseURL: "https://dribbbleapi.firebaseio.com",
projectId: "dribbbleapi",
storageBucket: "dribbbleapi.appspot.com",
messagingSenderId: "931058019229"
};
firebase.initializeApp(config);
You have to add it before the body tag closes like this:
<!doctype html>
<html>
<body>
...
<!-- Import and initialize the Firebase SDK -->
<script src="/__/firebase/3.7.4/firebase-app.js"></script>
<script src="/__/firebase/3.7.4/firebase-auth.js"></script>
<script src="/__/firebase/init.js"></script>
<script>
// The Firebase SDK is ready to rock!
firebase.auth().onAuthStateChange(function(user) { /* … */ });
</script>
</body>
</html>
So inside a script tag then close body and close html tag

Categories