I'm trying to request my firebase from a tizen web app. So I have added the firebase config to script section, then I need to access my firebase object from the javascript but I don't know how to proceed, how to declare 'firebase' variable to be linked to the firebase lib? here is my code :
tizen studio screenshot
or
function init() {
// How to get firebase object ?
firebase.database()
.ref('/test')
.once('value').then(function(snapshot) {
var value = snapshot.val();
document.querySelector("#foo")
.innerHTML = value;
});
...
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
content="width=device-width, initial-scale=1, user-scalable=no" />
<title>Hello Tizen</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "blabla",
authDomain: "blabla",
databaseURL: "blabla",
projectId: "blabla",
storageBucket: "blabla",
messagingSenderId: "blabla"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<div id="container">
<div id="contents">
<span id="foo">To replace </span>
</div>
</div>
<script src="js/app.js"></script>
</body>
</html>
EDIT :
adding <access origin="*" subdomains="true"></access> to config.xml solve my internet connection issue
You seem to have forgotten to put these scripts as well
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase-database.js"></script>
firebase-app.js should always come first.
Related
I want add to firebase SDK in external JavaScript file and link my JavaScript file with index.html and I want to create all functions in an external JavaScript file but after putting code of SDK my function is not working and no output appears in the console.
//code of main.js
import { initializeApp } from "firebase/app";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyBbXn11EFZ-B4UutkGbbvFFhddnqWFpDWc",
authDomain: "test-app-c0aed.firebaseapp.com",
projectId: "test-app-c0aed",
storageBucket: "test-app-c0aed.appspot.com",
messagingSenderId: "797893271922",
appId: "1:797893271922:web:5fc8bade62add0ca573deb"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const provider = new firebase.auth.GoogleAuthProvider();
// event and function for login button
document.getElementById('login').addEventListener("click",login);
function login()
{
console.log('login');
firebase.auth().signInWithPopup(provider).then( res => {
console.log(res);
})
}
// event and function for log out button
document.getElementById('logout').addEventListener("click",logout);
function logout(){
console.log('logout');
}
//code of 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">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<div id="dashboard">
<div id="userDetails">
<p>Welcome to dashboard</p>
</div>
<div id="logout">
<button id="logoutButton">Logout</button>
</div>
</div>
<div id="loginForm">
<button id="login">SignInWithGoogle</button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
try to add type="module" to script <script type="module" src="main.js"></script> and use local server to host index.html because module will not working when you just open index.html in browser file://
I want to get the data from my database using JavaScript and firebase, I have configured the firebase connection, but it gives me error: db is not defined.
I think the problem comes from the database configuration with firebase.
because the tutorial configuration is different than that.
I found this configuration in a post : previous solution
db.collection('courses').get()
.then(res => console.log(res))
.catch(err => console.error(err))
<!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>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>
<body>
<div class="container my-5">
<div class="row">
<div class="col-4 mx-auto">
<h3 class="my-3 text-center"><span class="badge badge-info">MARZOUK</span></h3>
<form>
<div class="input">
<div class="input-group">
<input type="text" class="form-control" id="course" placeholder="add new course">
<div class="input-group-apprend">
<input type="submit" class="btn btn-outline-secondary">
</div>
</div>
</div>
</form>
</div>
</div>
<ul class="list-group mt-2">
<li class="list-group-item">element</li>
<li class="list-group-item">element</li>
<li class="list-group-item">element</li>
</ul>
</div>
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.8.3/firebase-app.js';
import { getFirestore, collection, getDocs } from 'https://www.gstatic.com/firebasejs/9.8.3/firebase-firestore-lite.js';
const firebaseConfig = {
apiKey: "Myapikey",
authDomain: "javascript-3bbaa.firebaseapp.com",
projectId: "javascript-3bbaa",
storageBucket: "javascript-3bbaa.appspot.com",
messagingSenderId: "<myId>",
appId: "<MyappId>"
};
// Initialize Firebase
const firebase = initializeApp(firebaseConfig);
const db = getFirestore(firebase);
</script>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script src="script.js"></script>
</body>
</html>
const db = getFirestore(firebase);
You define db as the very last thing in your module. It then immediately falls out of scope and will be garbage collected.
If you want to use it, then you need to do so in the same scope.
Presumably the JS you put in the JavaScript box of your live demo is from <script src="script.js"></script>. Move it into the module where you define db.
It seems that I am unable to sign into an account that's on Firebase.
I honestly don't know what to try. I'm at a loss for what to do, as I am very new to Firebase.
Here is the code for signing in:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Log in</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form onsubmit="signin()">
<input id="email" type="email" name="email">
<input id="password" type="password" name="password">
<input type="submit" Value="Log in">
</form>
<script src="https://www.gstatic.com/firebasejs/5.8.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "api key",
authDomain: "domain",
databaseURL: "databaseurl",
projectId: "id",
storageBucket: "bucket",
messagingSenderId: "senderid"
};
firebase.initializeApp(config);
function signin() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
</script>
</body>
</html>
Then here is the code for the account page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 id="useremail"></h1>
<script src="https://www.gstatic.com/firebasejs/5.8.2/firebase.js"></script>
<script>
var config = {
apiKey: "api key",
authDomain: "domain",
databaseURL: "databaseurl",
projectId: "id",
storageBucket: "bucket",
messagingSenderId: "senderid"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
document.getElementById("useremail").innerHTML = "Logged in";
} else {
// No user is signed in.
document.getElementById("useremail").innerHTML = "Not logged in";
}
});
</script>
</body>
</html>
If you are signed into an account, the account page should display "Signed in" however it says that it isn't, even though I believe I have signed into an account using the sign in page.
Url of website: https://calculatingclutteredgreenware--mrsprinkletoes.repl.co/
I am trying to code something which allows we do store data into the database when the internet is available and also when the user disconnected and reconnects again. I tried to use the sample code to help me with this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<!--/meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" /-->
<!--/meta http-equiv="Content-Security-Policy" content="
default-src *;
style-src * 'unsafe-inline';
script-src * 'unsafe-inline';
"/-->
<!--/External/-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>DeeLight</title>
</head>
<body>
<button id="clickButton" type="submit"> Submit</button>
<div id="result"></div>
<script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyD41Ig37DIfH-MoF04cO4MYbcTYKL_wErQ",
authDomain: "fypfirebase.firebaseapp.com",
databaseURL: "https://fypfirebase.firebaseio.com",
projectId: "fypfirebase",
storageBucket: "fypfirebase.appspot.com",
messagingSenderId: "787149952533"
};
firebase.initializeApp(config);
// since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/004/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/004/lastOnline');
var connectedRef = firebase.database().ref('.info/connected');
connectedRef.on('value', function(snap) {
$("#clickButton").on("click", function writeUserData() {
if (snap.val() === true) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
var con = myConnectionsRef.push();
// Add this device to my connections list
// this value could contain info about the device or a timestamp too
con.set(true);
// When I disconnect, update the last time I was seen online
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
}
});
});
</script>
</body>
</html>
Basically, I create a button, data will be stored in the database (after clicking the button)when the internet is available.
Data can store into the database. When there is no internet and I clicked the button, the data will be stored in the database when after reconnected.
The problem comes when I click again (after reconnected), the function seems triggered two times. when I disconnect and reconnect again.. it triggered three times.
Click to see the generated result
Thank you for your help.
creating a onclick event inside a firebase on() stream just yells trouble to me can you try make these two independent and use a variable to track online status?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<!--/meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" /-->
<!--/meta http-equiv="Content-Security-Policy" content="
default-src *;
style-src * 'unsafe-inline';
script-src * 'unsafe-inline';
"/-->
<!--/External/-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<title>DeeLight</title>
</head>
<body>
<button id="clickButton" type="submit"> Submit</button>
<div id="result"></div>
<script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyD41Ig37DIfH-MoF04cO4MYbcTYKL_wErQ",
authDomain: "fypfirebase.firebaseapp.com",
databaseURL: "https://fypfirebase.firebaseio.com",
projectId: "fypfirebase",
storageBucket: "fypfirebase.appspot.com",
messagingSenderId: "787149952533"
};
firebase.initializeApp(config);
// since I can connect from multiple devices or browser tabs, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
var myConnectionsRef = firebase.database().ref('users/004/connections');
// stores the timestamp of my last disconnect (the last time I was seen online)
var lastOnlineRef = firebase.database().ref('users/004/lastOnline');
var connectedRef = firebase.database().ref('.info/connected');
var connectionStatus = false;
connectedRef.on('value', function(snap) {
connectionStatus=snap.val()
if(connectionStatus)
{
lastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
}
});
$("#clickButton").on("click", function writeUserData() {
if (connectionStatus) {
// We're connected (or reconnected)! Do anything here that should happen only if online (or on reconnect)
var con = myConnectionsRef.push();
con.set(true);
}
});
</script>
</body>
</html>
New to angular. Maybe I'm dense, but not sure anyone else is seeing the same problem I'm having despite my checks for the prescribed naming errors. I've used the convention Ctrl as shorthand for controller.
My Chat Controller ChatCtrl.js is as follows
angular.module("blocChat")
.controller("ChatCtrl", function($scope, Message, Room) {
$scope.roomName
$scope.rooms = Room.all
$scope.goToRoom = function(room) {
$scope.selectedRoom = room
console.log($scope.selectedRoom)
$scope.messages = Message.getByRoomId($scope.selectedRoom.id)
}
$scope.message = function() {
}
});
My Index.html is as follows:
<!DOCTYPE html>
<html ng-app="blocChat">
<head lang="en">
<meta charset="UTF-8">
<title>Bloc Chat Project</title>
<link rel="stylesheet" href="/styles/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans:400,800,600,700,300">
<link rel="stylesheet" type="text/css" href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="styles/normalize.css">
<!-- <link rel="stylesheet" href="/styles/landing.css"> -->
<link rel="stylesheet" href="/styles/home.css">
<link rel="stylesheet" href="/styles/room.css">
<link rel="stylesheet" type="text/css" href="/styles/style.css" />
</head>
<body class="home" ng-controller="ChatCtrl">
<!-- <ng-include src="'/templates/home.html'"></ng-include> -->
<h1>Bloc Chat</h1>
<h2>{{ roomName }}</h2>
<ul><li ng-repeat="room in rooms"><a ng-click="goToRoom(room)">{{ room.name }}</a></li></ul>
<h1>Room: {{ selectedRoom.name }}<h1>
<h2>Room Html<h2>
<div><li ng-repeat="message in messages"> {{ message.text }} </li></div>
<script data-require="angular.js#1.6.1" data-semver="1.6.1" src="https://code.angularjs.org/1.6.1/angular.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- ui's -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<!-- firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.6/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>
<!-- css -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css"></script> -->
<!-- app scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-cookies.js"></script>
<script src="/scripts/app.js"></script>
<script src="/scripts/controllers/ChatCtrl.js"></script>
<script src="/scripts/controllers/HomeCtrl.js"></script>
<script src="/scripts/controllers/RoomCtrl.js"></script>
<script src="/scripts/controllers/UsernameCtrl.js"></script>
<script src="/scripts/factory/Message.js"></script>
<script src="/scripts/factory/Room.js"></script>
</body>
</html>
This happened around the time I created the following file, but I've been advised this is probably just coincidence, UsernameCtrl.js:
angular.module("blocChat", ['ui.bootstrap'])
.controller("UsernameCtrl", function($scope, $uibModal) {
$uibModal.open({
controller: "ModalCtrl",
templateUrl: "/templates/username.html"
})
})
.controller("ModalCtrl", function($uibModalInstance, $scope) {
$scope.user = {
username: "John",
password: "test"
}
})
.run(function($uibModal) {
$uibModal.open({
controller: "ModalCtrl",
templateUrl: "/templates/username.html"
})
})
My code in app.js:
angular
.module('blocChat', ['firebase', 'ui.bootstrap'])
.config(function($locationProvider) {
var config = {
apiKey: // Firebase API key
authDomain:// Firebase Auth domain ("*.firebaseapp.com")
databaseURL: // Firebase Database URL("https://*.firebaseio.com")
storageBucket: "bloc-chat-117d5.appspot.com",
messagingSenderId: "324260113714"
};
firebase.initializeApp(config);
})
my overall code is here: https://github.com/seanbode/bloc-chat
I've tried it with and without the [] in ChatCtrl.js when I call angular.module("blocChat"). I appreciate any advice you can give me as I understand I have a lot to learn in the ways of coding. Thank you.
You are declaring the same module twice
Without the second argument anguler.module('moduleName') is a getter. But with the dependency injection argument it is a setter.
Change:
angular.module("blocChat", [])
To
angular.module("blocChat")
Or move the dependency injection to this declaration since order of script loading has this one loading first