db.collection(...).set is not a function - javascript

I am trying to make when someone logs in my site update or create statistics.
I have this code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-auth.js"></script>
</head>
<body>
<script>
var firebaseConfig = {
apiKey:
authDomain:
databaseURL:
projectId:
storageBucket:
messagingSenderId:
appId:
};
firebase.initializeApp(firebaseConfig)
var db = firebase.firestore();
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
db.collection("users").set({
points: 0,
CurrentLevel: 0
})
}
});
console.log(user.points);
</script>
</body>
</html>
It should be working but when I try to run it, it says in the console db.collection(...).set is not a function
What Can I Do?

db.collection("users") returns an object of CollectionReference. CollectionReference has no function 'set', Hence the error.
Perhaps you are looking for the function 'add' which adds documents.
Replace
db.collection("users").set({
points: 0,
CurrentLevel: 0
})
with
db.collection("users").add({
points: 0,
CurrentLevel: 0
})
And I think that should solve your problem

Related

Joining meeting timeout issue on Zoom API

I’m using Academy LMS script with Academy LMS Live Class (zoom) Addon.
This addon asked me to enter api key and security key, I did.
Then I start a meeting via the zoom app and save the id and password to the system as a teacher.
When i try to connect a meeting as a student i get this error: “Joining meeting timeout. Your connection has timed out and you cannot join the meeting. Verify your network connectivity and try again.”
Please help me on this issue, thanks.
Thats my code:
<!DOCTYPE html>
<head>
<title>Zoom</title>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="https://source.zoom.us/1.7.7/css/bootstrap.css"/>
<link type="text/css" rel="stylesheet" href="https://source.zoom.us/1.7.7/css/react-select.css"/>
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body>
<script src="https://source.zoom.us/1.7.7/lib/vendor/react.min.js"></script>
<script src="https://source.zoom.us/1.7.7/lib/vendor/react-dom.min.js"></script>
<script src="https://source.zoom.us/1.7.7/lib/vendor/redux.min.js"></script>
<script src="https://source.zoom.us/1.7.7/lib/vendor/redux-thunk.min.js"></script>
<script src="https://source.zoom.us/1.7.7/lib/vendor/jquery.min.js"></script>
<script src="https://source.zoom.us/1.7.7/lib/vendor/lodash.min.js"></script>
<script src="https://source.zoom.us/zoom-meeting-1.7.7.min.js"></script>
<script>
$( document ).ready(function() {
start_zoom();
});
function start_zoom() {
ZoomMtg.preLoadWasm();
ZoomMtg.prepareJssdk();
testTool = window.testTool;
var meetConfig = {
apiKey: 'Existing Values',
apiSecret: 'Existing Values',
meetingNumber: 'Existing Values',
userName: 'Existing Values',
passWord: 'Existing Values',
};
var signature = ZoomMtg.generateSignature({
meetingNumber: meetConfig.meetingNumber,
apiKey: meetConfig.apiKey,
apiSecret: meetConfig.apiSecret,
role: 0,
success: function(res){
console.log(res.result);
}
});
ZoomMtg.init({
leaveUrl: "file:///C:/Users/User/Desktop/zoom.html",
isSupportAV: true,
success: function () {
ZoomMtg.join(
{
meetingNumber: meetConfig.meetingNumber,
userName: meetConfig.userName,
signature: signature,
apiKey: meetConfig.apiKey,
passWord: meetConfig.passWord,
success: function(res){
console.log('join meeting success');
},
error: function(res) {
console.log(res);
}
}
);
},
error: function(res) {
console.log(res);
}
});
}
</script>
</body>
</html>
My Error : “Joining meeting timeout. Your connection has timed out and you cannot join the meeting. Verify your network connectivity and try again”
Error Image:
enter image description here

How do I call Javascript code from Dart and register the callback in my console?

I have a Javascript file that I'm calling in my Flutter Webview Plugin.
I am trying to return the callback in the console after the onReward method is called. This is the code of my js file:
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="https://s3.amazonaws.com/cdn.theoremreach/v3/theorem_reach.min.js"></script>
</head>
<body>
<iframe src="https://theoremreach.com/respondent_entry/direct?api_key=845783b32b8bef12f1b55a36a8be&user_id=12345"></iframe>
<script type="text/javascript">
var theoremReachConfig = {
apiKey: "",
userId: "12345",
onRewardCenterOpened: onRewardCenterOpened,
onReward: onReward,
onRewardCenterClosed: onRewardCenterClosed
};
var TR = new TheoremReach(theoremReachConfig);
function onRewardCenterOpened(){
console.log("onRewardCenterOpened");
}
function onReward(data){
console.log("onReward: " + data.earnedThisSession);
}
function onRewardCenterClosed(){
console.log("onRewardCenterClosed");
}
if (TR.isSurveyAvailable()) {
TR.showRewardCenter();
}
</script>
</body>
</html>
And this is how I'm calling it in my Dart file:
...
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Reward earned"), actions: [
Text("$reward"),
]),
body: WebViewPlus(
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
controller.loadAsset(
'assets/tr.html',
);
},
));
}
When I complete a survey I get the following message in my console:
I/chromium( 3560): [INFO:CONSOLE(28)] "onReward: 2", source: http://localhost:56537/assets/tr.html (28)
I want to scan this console message and just add the value of the reward, i.e. 2, in my existing page and display it in the appBar.

How to fix Expected a value of type 'FirebaseError', but got one of type 'DomException' in Flutter web setting up push notifications?

I'm trying to set up firebase notifications in flutter web. I followed this medium article and I was able to do the basic set up.
But when a user clicks allow to give permissions, I'm getting this error.
Expected a value of type 'FirebaseError', but got one of type 'DomException'
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Lorem ipsum">
<meta name="robots" content="noindex">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Flutter web notifications">
<meta id="flutterweb-theme" name="theme-color" content="#393557">
<link rel="icon" type="image/png" href="/icons/Icon-192.png">
<link rel="apple-touch-icon" href="/icons/Icon-192.png">
<title>Flutter web notifications</title>
<link rel="manifest" href="./manifest.json">
</head>
<body id="app-container">
<!-- 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 -->
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-messaging.js"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
// navigator.serviceWorker.register('/flutter_service_worker.js');
navigator.serviceWorker.register("./firebase-messaging-sw.js");
});
}
</script>
<script src="https://www.gstatic.com/firebasejs/7.11.0/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<!-- <script src="/__/firebase/init.js"></script> -->
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
This is the firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.9.1/firebase-messaging.js");
var firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("New Message");
});
return promiseChain;
});
self.addEventListener('notificationclick', function (event) {
console.log('notification received: ', event)
});
This is the firebase_messaging.dart
import 'dart:async';
import 'package:firebase/firebase.dart' as firebase;
class FBMessaging {
FBMessaging._();
static FBMessaging _instance = FBMessaging._();
static FBMessaging get instance => _instance;
// firebase.Messaging _mc;
var _mc;
String _token;
final _controller = StreamController<Map<String, dynamic>>.broadcast();
Stream<Map<String, dynamic>> get stream => _controller.stream;
void close() {
_controller?.close();
}
Future<void> init() async {
_mc = firebase.messaging();
_mc.usePublicVapidKey('FCM_SERVER_KEY');
_mc.onMessage.listen((event) {
_controller.add(event?.data);
});
}
Future requestPermission() {
// await init();
return _mc.requestPermission();
}
Future<String> getToken([bool force = false]) async {
if (force || _token == null) {
// await requestPermission();
_token = await _mc.getToken();
}
return _token;
}
}
This is how I'm requesting permissions from the user
final _messaging = FBMessaging.instance;
() async {
_messaging
.init()
.then((_) async {
await _messaging
.requestPermission()
.then((_) async {
final _token =
await _messaging
.getToken();
print('Token: $_token');
});
});
}
But this is the error I'm getting when user clicks on allow
Error: Expected a value of type 'FirebaseError', but got one of type 'DomException'
at Object.throw_ [as throw] (http://localhost:44987/dart_sdk.js:4461:11)
at Object.castError (http://localhost:44987/dart_sdk.js:4432:15)
at Object.cast [as as] (http://localhost:44987/dart_sdk.js:4748:17)
at dart.AnonymousJSType.new.as (http://localhost:44987/dart_sdk.js:6186:64)
at handleThenable (http://localhost:44987/packages/firebase/src/storage.dart.lib.js:3264:96)
at handleThenable.throw (<anonymous>)
at http://localhost:44987/dart_sdk.js:36909:38
at _RootZone.runBinary (http://localhost:44987/dart_sdk.js:36762:58)
at _FutureListener.thenAwait.handleError (http://localhost:44987/dart_sdk.js:31933:48)
at handleError (http://localhost:44987/dart_sdk.js:32475:51)
at Function._propagateToListeners (http://localhost:44987/dart_sdk.js:32498:17)
at _Future.new.[_completeError] (http://localhost:44987/dart_sdk.js:32354:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:44987/dart_sdk.js:32392:31)
at Object._microtaskLoop (http://localhost:44987/dart_sdk.js:37015:13)
at _startMicrotaskLoop (http://localhost:44987/dart_sdk.js:37021:13)
1. Register your app at Firebase Console
2. Generate new Pair Key at Firebase Console
Tutorial: https://firebase.google.com/docs/cloud-messaging/js/client#generate_a_new_key_pair
3. Use your Pair Key
Copy your already generated Pair Key to the 'FCM_SERVER_KEY' (instead of your FCM SERVER KEY).
Future<void> init() async {
_mc = firebase.messaging();
_mc.usePublicVapidKey('FCM_SERVER_KEY');
_mc.onMessage.listen((event) {
_controller.add(event?.data);
});
}

Firebase phone number authentication on web

I tried this code for making Firebase phone number authentication:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Firebase Phone Number Auth
</title>
</head>
<body>
Updated
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script>
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign- in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
}); firebase.auth().signInWithPhoneNumber("+91XXXXXXXXXX", window.recaptchaVerifier)
.then((confirmationResult) => {
// At this point SMS is sent. Ask user for code.
alert('A confirmation message was just sent.');
var code = window.prompt('Please enter the 6 digit code');
return confirmationResult.confirm(code);
}).then((result) => {
console.log(result);
// User is now signed in and accessible via result.user.
}).catch((error) => {
// Error occurred.
});
</script>
</body>
</html>
But it's not working.
I'm a real newbie on Firebase. Please somebody help.
(Note: you can also test it on Localhost.)
The code is live at https://GroupinGer.cu.ma/ph/
Also, I would like to show the user data(Phone number, UID etc.) In another file called details.html.
I tried this code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Logged in</title>
</head>
<body>
Your details are shown below.
<br>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script>
var credential = firebase.auth.PhoneAuthProvider.credential(confirmationResult.verificationId, code);
alert(credential);
alert('nope.');
</script>
</body>
</html>
Please have a look at it too.
Again, thanks a lot.
First of all, you need to initialize a recaptchaVerifier like this:
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-
in-button', {
'size': 'invisible',
'callback': function(response) {
// reCAPTCHA solved, allow signInWithPhoneNumber.
onSignInSubmit();
}
});
Second, your code has syntax error. Try the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase Phone Number Auth</title>
</head>
<body>
<form>
<input type="text" id="verificationcode" value="enter verification">
<input type="button" value="Submit" onclick="myFunction()">
</form>
<div id="recaptcha-container"></div>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script type="text/javascript">
// Initialize Firebase
var config = {
apiKey: "AIzaSyAL8dSTuXb92DWu0l78dtV4m4fC8psKeV4",
authDomain: "groupinger-users.firebaseapp.com",
databaseURL: "https://groupinger-users.firebaseio.com",
projectId: "groupinger-users",
storageBucket: "groupinger-users.appspot.com",
messagingSenderId: "432661298034"
};
firebase.initializeApp(config);
</script>
<script type="text/javascript">
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
firebase.auth().signInWithPhoneNumber("replace with your phone number with country code, start with +1 if US.", window.recaptchaVerifier)
.then(function(confirmationResult) {
window.confirmationResult = confirmationResult;
console.log(confirmationResult);
});
var myFunction = function() {
window.confirmationResult.confirm(document.getElementById("verificationcode").value)
.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error);
});
};
</script>
</body>
</html>
For more details, you can refer to the phone auth part of firebase auth doc.
https://firebase.google.com/docs/auth/web/phone-auth

Unable to initialise firebase in my html file and save any data to realtime database

I am trying to learn firebase. But i am unable to save my input to the firebase database because it is not getting initialized even after adding all the required script that I know. Here is my entire code
PS: authentication to my database was also turned off for learning purpose. So it must not be any issue with authentication.
<!DOCTYPE html>
<html>
<head>
<title>Learning Firebase</title>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script type="text/javascript">
var config = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxxxx",
databaseURL: "xxxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxxx",
messagingSenderId: "xxxxxxx"
};
firebase.initializeApp(config);
var text=documentgetElementById('text').value;
function validate(){
var database=firebase.database().ref();
database.child("text").set(text);
}
</script>
</head>
<body>
<form onsubmit="validate();">
Text:<input type="text" id='text'/>
<input type='submit' value='save'/>
</form>
</body>
Your problem is not with your Firebase code, it is about your JavaScript code. Replace this code below and try it again:
<!DOCTYPE html>
<html>
<head>
<title>Learning Firebase</title>
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script type="text/javascript">
var config = {
apiKey: "xxxx",
authDomain: "xxxx",
databaseURL: "xxxx",
projectId: "xxxx",
storageBucket: "",
messagingSenderId: "xxxx"
};
firebase.initializeApp(config);
function validate(){
var yourNewChildValue=document.getElementById('text').value;
var database=firebase.database().ref();
database.child("yourNewChildKey").set(yourNewChildValue);
}
</script>
</head>
<body>
<form>
Text:<input type="text" id='text'/>
<input type='button' onclick="validate();" value='save'/>
</form>
</body>
It must be save your data to Firebase database if your credentials are true. Please let me know.

Categories