I am trying to make a basic firebase database app and continue to get 3 errors that I don't know how to fix. The errors are:
Uncaught SyntaxError: Unexpected token 'export' (at firebase-app.js:2348:1)
Uncaught SyntaxError: Cannot use import statement outside a module (at firebase-storage.js:1:1)
storage.js:16 Uncaught ReferenceError: firebase is not defined
at storage.js:16:2 ()
at storage.js:58:2
For #3 storage.js:16:2 points to firebase.initializeApp(firebaseConfig) code and storage.js:16:2 point to the } at the end of the code, }());. I have attached my code and images of the errors I am getting. Please help!
(function(){
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBFZQE-zC4QNu3ooZE7VygTN83g7su-wIc",
authDomain: "courso-43b7d.firebaseapp.com",
databaseURL: "https://courso-43b7d.firebaseio.com",
projectId: "courso-43b7d",
storageBucket: "courso-43b7d.appspot.com",
messagingSenderId: "373899831879",
appId: "1:373899831879:web:d76aa2fbd69529cabb9f62"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// handle on firebase db
var db = firebase.database();
// get elements
var message = document.getElementById('message');
var write = document.getElementById('write');
var read = document.getElementById('read');
var status = document.getElementById('status');
// write
write.addEventListener('click', e => {
var messages = db.ref('messages');
// simple id - ok for example, do not use in production
var id = (new Date).getTime();
// write to db
messages.child(id).set({'message' : message.value})
.then(function(){
status.innerHTML = "Wrote to DB!";
});
});
// read
read.addEventListener('click', e => {
status.innerHTML = '';
var messages = db.ref('messages');
messages.once('value')
.then(function(dataSnapshot) {
var data = dataSnapshot.val();
var keys = Object.keys(data);
keys.forEach(function(key){
console.log(data[key]);
status.innerHTML += JSON.stringify(data[key]) + '<br>';
});
});
});
}());
<!DOCTYPE html>
<html>
<head>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/9.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.8.0/firebase-database.js"></script>
</head>
<input id="message" type="text" placeholder="Text to write to DB"><br>
<button id="write">Write</button>
<button id="read">Read</button><br>
<div id="status"></div>
<script src="database.js"></script>
</html>
Dev Tools SyntaxErrors
Related
I would like to make a web app using Firebase Hosting.
make audio file using Cloud text to speech API
upload that audio file to Cloud Storage
download that audio file from Cloud Storage to a web browser
I passed step 1 and 2, but have a trouble with step 3.
I followed this turorial.
https://firebase.google.com/docs/storage/web/download-files
I deployed my Firebase project and tested my app. I could upload audio file to Cloud Storage, but I couldn't download it. I looked at browser's console, but I couldn't find any error message. There was no message in browser's console.
Could you give me any advice? Thank you in advance.
This is my main.js
'use strict';
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
return firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
// Checks that the Firebase SDK has been correctly setup and configured.
function checkSetup() {
if (!window.firebase || !(firebase.app instanceof Function) || !firebase.app().options) {
window.alert('You have not configured and imported the Firebase SDK. ' +
'Make sure you go through the codelab setup instructions and make ' +
'sure you are running the codelab using `firebase serve`');
}
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
// Create a reference from a Google Cloud Storage URI
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
This is index.js (Cloud Functions)
const functions = require('firebase-functions');
var admin = require("firebase-admin");
admin.initializeApp();
const textToSpeech = require('#google-cloud/text-to-speech');
exports.myFunction = functions.firestore
.document('messages/{id}')
.onCreate((change, context) => {
const client = new textToSpeech.TextToSpeechClient();
async function quickStart() {
// The text to synthesize
const text = 'Hello world';
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
var bucket = admin.storage().bucket('adva********.appspot.com');
var file = bucket.file('audio/sub.mp3')
// Create the file metadata
var metadata = {
contentType: 'audio/mpeg'
};
// Performs the text-to-speech request
const [response] = await client.synthesizeSpeech(request);
return await file.save(response.audioContent, metadata)
.then(() => {
console.log("File written to Firebase Storage.")
return;
})
.catch((error) => {
console.error(error);
});
}
quickStart();
});
This is index.html
<!--./advance/index.html-->
<!doctype html>
<html lang="ja">
<head>
<meta name="robots" content="noindex">
<title>音読アプリ アドバンス</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=M+PLUS+Rounded+1c&display=swap" rel="stylesheet">
<style>
#text {width: 100%; height: 300px; font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 22px;}
#download {font-family: 'M PLUS Rounded 1c', sans-serif; font-size: 28px;}
</style>
</head>
<body>
<textarea id="text" class="form-control" name="text" placeholder="ここに英文を入力してください。" maxlength="3000" minlength="1"></textarea>
<br>
<div style="text-align:center">
<input id="download" class="btn btn-primary" type="submit" value="音声をダウンロード">
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<!-- Import and configure the Firebase SDK -->
<!-- These scripts are made available when the app is served or deployed on Firebase Hosting -->
<!-- If you do not want to serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup -->
<script src="/__/firebase/7.14.3/firebase-app.js"></script>
<script src="/__/firebase/7.14.3/firebase-auth.js"></script>
<script src="/__/firebase/7.14.3/firebase-storage.js"></script>
<script src="/__/firebase/7.14.3/firebase-messaging.js"></script>
<script src="/__/firebase/7.14.3/firebase-firestore.js"></script>
<script src="/__/firebase/7.14.3/firebase-performance.js"></script>
<script src="/__/firebase/7.14.3/firebase-functions.js"></script>
<script src="/__/firebase/init.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
browser's developer tool's Network tab
The problem is that you are likely trying to download before the file is created by your cloud function, since you are running the cloud function as a event trigger that automatically runs every time a document is created, but at the same time you are trying to download that file on your front end. This lack of syncronism creates this odd behaviour you are seeing.
In order to fix that there are a couple of things you should do:
Convert your cloud function to a http triggered function instead of a event triggered function.
This will make it so your function can be invoked by your front end after the creation of the document and before you are trying to download it, it could look like this:
exports.myFunction = (req, res) => {
//you can get the id of the document sent on the request here
const id=req.body;
...
};
Also, you might want to check this documentation for more details on this type of trigger
Create a download function and add all your code for the download to it and add synchronicity to your operations on your front-end.
With this your code will execute in the proper order, and you main.js will look like this:
// Saves a new message on the Cloud Firestore.
function saveMessage() {
// Add a new message entry to the Firebase database.
firebase.firestore().collection('messages').add({
text: messageInputElement.value,
timestamp: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function(docRef){
var obj = {
method: 'POST',
body: docRef.id
};
//calls function that adds to storage
fetch("YOUR_FUNTION_URL_HERE", obj).then({
//actually downloads
download();
}).catch(error) {
console.error('Failed to call cloud function', error);
});
}).catch(function(error) {
console.error('Error writing new message to Firebase Database', error);
});
}
function download(){
var storage = firebase.storage();
var gsReference = storage.refFromURL('gs://advan********8.appspot.com/audio/sub.mp3')
gsReference.getDownloadURL().then(function(url) {
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/object-not-found':
console.log('storage/object-not-found')
break;
case 'storage/unauthorized':
console.log('storage/unauthorized')
break;
case 'storage/canceled':
console.log('storage/canceled')
break;
case 'storage/unknown':
console.log('storage/unknown')
break;
}
});
}
// Checks that Firebase has been imported.
checkSetup();
// Shortcuts to DOM Elements.
var messageInputElement = document.getElementById('text');
var submitButtonElement = document.getElementById('download');
// Saves message on form submit.
submitButtonElement.addEventListener('click', saveMessage);
NOTE: This is all untested but it will be a good starting point for your to start the changes necessary to your code.
I hope someone may still find this useful. A hack around is to create an express server/lambda/cloud function to download file and send it back to the browser via the download method. Check bellow code
const express = require("express");
const app = express();
var fs = require("fs");
const request = require("request");
app.get("/", (req, res) => {
const { filename, fileUrl } = req.body;
const file = fs.createWriteStream("filename");
request.get(fileUrl).on("response", function (response) {
var pipe = response.pipe(file);
pipe.on("finish", function () {
res.download(filename, function (err) {
if (err) {
console.log(err); // Check error if you want
}
fs.unlink(yourFilePath, function () {
console.log("File was deleted"); // Callback
});
});
});
});
});
app.listen(3000, () => console.log("Server ready"));
<!-- begin snippet: js hide: false console: true babel: false -->
var unSubscribe=firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.location.replace("library.html");
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
//document.getElementById("user_para").innerHTML = "Welcome User : " + email_id;
}
} else {
// No user is signed in.
window.location.replace("index.html");
}
unSubscribe();
});
function login(){
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
function logout(){
firebase.auth().signOut();
}
<html>
<head>
<title>Firebase Login</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="login_div" class="main-div">
<h3>Firebase Web login Example</h3>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password..." id="password_field" />
<button onclick="login()">Login to Account</button>
</div>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-firestore.js"></script>
<script>
// Initialize Firebase
var firebaseConfig = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId:,
appId: ,
measurementId:
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script src="index.js"></script>
</body>
</html>
(library.html also has the same script tags.)
I have seen similar questions and the answers to them were to call the function returned by firebase.auth().onAuthStateChanged(), so I implemented that but the index.html page keeps reloading multiple times. I have implemented the functionality for a single html page by hiding and displaying elements and it worked fine before.
I have also tried inserting the window.location.replace() in the login and logout functions but that on browser gives a blank html page and no errors on inspect.
Please help me with the issue, I am a beginner at javascript and web development.
You say both HTML pages have the same script running. So when you redirect to either page, the code will run again, trying to redirect you again.
If this is indeed the problem, a quick fix might be to pass a query param like redirect=true, and then only execute the code when this param is false.
window.location.replace("library.html?redirect=true");
then parse your url with a regex f.e.
const wasRedirected = new Regex(/[?&]redirect=(true|false)/g).exec(window.location)[1] === 'true'
firebase.auth().onAuthStateChanged() function sets an observer on the Auth Object. And as an observer, it continuously checks for the state of the authorization. That's why the index.html page keeps on reloading. The solution is to call the onAuthStateChanged() function only one time when your window reloads for the first time. Add the following code in the index.js file.
window.onload = unSubscribe;
Hope it helps.
I am trying to execute a simple function to execute what a users email is. If I delete everything in the javascript file besides the function itself everything works just fine, can anyone spot an issue with this code that would cause this to break? How should I initialize firebase in one javascript file so that I can reuse the initialization across multiple files?
HTML:
<head>
<script type="text/javascript" src="/JS/getUsersNameR.js"></script>
</head>
<span>Welcome, <strong><script>usersEmail()</script></strong></span><br>
JS:
var firebase = require("firebase");
var $;
$ = require('jquery');
require("firebase/firestore");
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
var user = firebase.auth().currentUser;
var email;
if (user) {
// User is signed in.
email = user.email;
alert("TEST");
} else {
// No user is signed in.
}
function userEmail() {
document.write("TEST");
}
I guess the path of your js reference is wrong. Double check the path. Otherwise the code looks good
DEMO
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function usersEmail() {
document.write("TEST");
}
</script>
</head>
<body>
<script type="text/javascript">
usersEmail();
</script>
</body>
</html>
don't call the function through a script tag, if you want to call a function when the page loads use the body tag's onload attribute. example:
<body onload="myFunction();"><div id="myText">other code</div></body>
and have the myFunction() function set the text value of a certain id to whatever you want. Example:
function myFunction(){
document.getElementById("myText").innerHTML = "My text";
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
console.log("Hurray ! signed in successfully !");
} else {
// No user is signed in.
console.log("Sign in required !");
$("#login-btn-nav").click();
}
});
$("#login-btn").on('click',function(){
console.log("Hello");
var email = $("#email-input").val();
var password = $("#password-input").val();
if(email != "" && password != ""){
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
window.alert("Following error encountered : "+errorMessage+" .");
});
}
});
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.2.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDAvfWcdBTtmDbK7_aOkWFCRxNl1K4PDck",
authDomain: "sarahhah-8e315.firebaseapp.com",
databaseURL: "https://sarahhah-8e315.firebaseio.com",
projectId: "sarahhah-8e315",
storageBucket: "sarahhah-8e315.appspot.com",
messagingSenderId: "965679781332"
};
firebase.initializeApp(config);
console.log(config);
</script>
<script type="text/javascript" src="assets/js/login.js"></script>
copied the web code snipets ans pasted in the html code as attached and javascript code is also attached !
facing error as :
A network error (such as timeout, interrupted connection or unreachable host) has occurred. .
in web integration of firebase
thanks in advance for your cooperation
I will duplicate an answer from comments from Rahul Sharma because this saved me a lot of time. Hope this will help somebody else:
Use <div> instead of <form> tag
Hello I am trying to make a web site utilizing Firebass as my back end but I am having trouble reading data from the data base. I've double checked the paths and yes there is data there. If someone could give a quick look at what I am doing wrong I would really appreciate it. I am not getting any errors, its just not working.
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app.firebaseio.com",
storageBucket: "my-ap.appspot.com",
messagingSenderId: "123456789"
};
</script>
<script>
function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
console.log("Working");
console.log("lat:" + snapshot.val().latitude);
});
}
</script>
</head>
<body onload="main();">
hello
</body>
</html>
To read from database, you need 2 callbacks, 1 for reading, 1 for errors. This will work for you:
firebase.database().ref("users/rates").once('value', readFn(),errFn(errorObject))
or replace main with this
function main(){
firebase.initializeApp(config);
var database = firebase.database();
var ratesRef = database.ref("users/rates");
ratesRef.on('child_added', function(snapshot){
console.log("Working");
console.log("lat:" + snapshot.val().latitude);
}, function(err) {console.log(err)});
}
You should also use once to prevent reading more than once when you request it
First of all log your errors to see what happens.
ratesRef.once('value')
.then(function(snap){...})
.catch(function(err){console.log(err)})
Very probably you are getting permissions denied error as your security rules by default allow access for authenticated user.