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
Related
I'm following the Firebase Firestore tutorial located at https://firebase.google.com/docs/firestore/quickstart to learn how to use the Firestore No- SQL document store.
I built the simple app using the npx webpack –watch command so I could refresh the page and get updated changes on the fly. Webpack puts the main.js or bundle.js file in the dist folder of the project root.
I have made several changes to the 'index.html' script tag in vain to get the app working.
If I use <script src=”dist/main.js”></script> or <script src=”main.js”></script> I get the following:
If I use:
<script src=”index.js”></script> I get the following error:
So I used the <script type=module attribute.
If I use: <script type=module src="index.js"></script> I get the following:
So I thought I would put a "/" and a "./" in front of index.js
If I use: <script type=module src="/index.js"></script> or <script type=module src="./index.js"></script>
I get the same error as above:
What's going on here?
Here is the file structure:
Project Root
>dist
-main.js
>node_modules
>src
-index.html
-index.js
>package.json
>package-lock.json
>webpack.config.js
Here are the key files:
index.html
<!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>My Simple Cafe</title>
</head>
<body>
<p>
<h2>Hello Firestore!</h2>
</p>
<script type=module src="index.js"></script>
</body>
</html>
index.js
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore, doc, setDoc } from "firebase/firestore";
import { getAnalytics } from "firebase/analytics"
// 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: <apiKey>
authDomain: <authDomain>
databaseURL: <databaseURL>
projectId: <projectId>
storageBucket: <storageBucket>
messagingSenderId: <messagingSenderId>
appId: <appId>
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const firestore = getFirestore();
const specialOfTheDay = doc(firestore, 'dailySpecial/2021-09-14')
function writeDailySpecial(){
const docData = {
description: 'A delicious vanilla latte',
price: 3.99,
milk: 'Whole',
vegan: false,
};
setDoc(specialOfTheDay, docData)
}
console.log("Hello , Firestore!")
writeDailySpecial();
webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: '/src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
}
}
package.json
{
"dependencies": {
"firebase": "^9.0.2"
},
"devDependencies": {
"serve": "^13.0.2",
"webpack": "5.52.1",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.7.2"
},
"name": "simplecafe",
"version": "1.0.0",
"description": "Tutorial from https://firebase.google.com/docs/firestore/quickstart",
"main": "index.js",
"scripts": {
"test": "echo\"Error: no test specified\" && exit 1",
"build": "webpack"
},
"author": "Todd Kerpelman",
"license": "ISC"
}
Thanks in advance.
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.
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>
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);
})
}
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