I am trying to make a JavaScript Announcement which includes a function main() in this case, that is not triggering upon onload function in the body tag I have inserted, , but when I manually trigger this function in Chrome's Console, it works as expected, please help me..
I have Also Used Firebase's Realtime Database for one of the values out of more values that I will use from there..
Code:
Here is the HTML & JS
or you can see the Code:
HTML:
// Firebase Setup
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var firebaseConfig = {
apiKey: "AIzaSyBz2pk-ec0yn7H25fzLaXI13CmAX4xp1-o",
authDomain: "learningdb-1.firebaseapp.com",
databaseURL: "https://learningdb-1-default-rtdb.firebaseio.com",
projectId: "learningdb-1",
storageBucket: "learningdb-1.appspot.com",
messagingSenderId: "287578856127",
appId: "1:287578856127:web:0894a806aa5b039bafc40a",
measurementId: "G-682XPG49J1"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Add .child('the reference of the value you want to see like dbRef.on')
var dbRef = firebase.database().ref();
let announcements;
var ann = firebase.database().ref().child('announcements');
ann.on('value', snap => announcements = snap.val());
// /Firebase Setup and Inialization Complete!
// announcements = true;
function main() {
if (announcements == true) {
mainAnnouncement = "AVMC has decided to recontinue the Minecraft Network services and is expected to be up by 20-25 March. This given date may be extended seeing the amount of potential problems in the Network as of being down for a good time. There will be tests done with some feature updates and more before going up! ";
announcementTitle = "Important Notice! ";
jsPara = document.getElementById('jsId');
jsPara2 = document.getElementById('jsPara')
jsPara.innerHTML += `Announcements is set to "${announcements}" <br>
<b> [ANNOUNCEMENT BODY] </b> <br>`;
jsPara2.innerHTML +=
`<div class="alert alert-warning" role="alert">
<h5>
<b>${announcementTitle}</b>
</h5>
<hr>
${mainAnnouncement}
</div>`
} else if (announcements == false) {
jsPara = document.getElementById('jsId');
jsPara.innerHTML = `Announcements is set to "${announcements}"`;
}
}
<!DOCTYPE html>
<html>
<head>
<title>LearningDB-1 | AVMC</title>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.3.0/firebase-database.js"></script>
<script src="js/index.js"></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
</head>
<body onload="main()">
<br>
<div class="container">
<h4><u><b>This code triggers an Announcement
when the value "announcement" is set to "true"</u></b></h4>
<h5 id="jsId"><b> [ANNOUNCEMENT] </b></h5>
<div id="jsPara"></div>
</body>
</script>
</html>
My goal is to build a WebGL game in Unity that has a specific form and upon submission that form posts data into one of the Firebase storage solutions. After reading this article, it's clear to me I need to use Cloud Firestore instead of Realtime Database. Good news is that as of of March 2020, one of the team members wrote,
we released Firebase Unity SDK 6.12.0 which includes an alpha release
of Firestore.
Thing is, Firebase's Unity SDK isn't for WebGL builds and, for someone going through that thought process, could use Firebase JS SDK (spam alert). From looking at the release notes, one can see that Firebase JS SDK supports Firestore and so this has all the conditions in place for a quick solution.
So, I've gone to Firebase console, created a project, a Web app to use Firebase JS SDK and this process gave as output the following code
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/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.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
with a message saying
Copy and paste these scripts into the bottom of your tag, but
before you use any Firebase services
In addition to that, this is how to Call JavaScript functions from Unity scripts and this is a Cloud Firestore JS Sample App.
Given this information, how can then the form be created?
Let's say you want a form that receives as input
String
Number
Text from the user
In your Firestore console, create a collection and give it a name (like formDataTree), give an autoID and add the fields
strVal
intVal
webVal
Then, I would put those scripts at the bottom of the head tag in your WebGL template. So, create a folder in Assets named WebGLTemplates, and a folder named New Template (or whatever name you will) and add an index.html there.
According to the documentation, this index.html should be similar to
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
</head>
<body>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
</body>
</html>
So, with this new information, it'll be something like this
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Unity WebGL Player | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/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.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
</head>
<body>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
</body>
</html>
Then, under Player settings, select that template.
Then in the body of the template, have a form with its visibility to hidden. Include things from the game as well as any inputs you want filled out in the browser:
<form id="webForm" style="visibility:hidden;">
<input type="hidden" id="stringInput" name="stringInput">
<input type="hidden" id="intInput" name="intInput">
<label for="webInput">web input</label><input type="text" id="webInput" name="webInput">
<button type="submit">Submit</button>
</form>
Then below the Firebase script and the form, include a submit listener for the form on the page which will submit it to Firestore (based on this answer):
myForm.addEventListener('submit', function(evt) {
evt.preventDefault(); //Prevent the default form submit action
var strVal = myForm.stringInput.value;
var intVal = myForm.intInput.value;
var webVal = intInput.webInput.value;
var formData = {
"strVal" : strVal,
"intVal" : intVal,
"webVal" : webVal
};
firebase.database().ref('/formDataTree').push( formData ); // Adds the new form data to the list under formDataTree node
});
All in all, the index.html should be something like this
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Change Mapping | %UNITY_WEB_NAME%</title>
<script src="%UNITY_WEBGL_LOADER_URL%"></script>
<script>
var unityInstance = UnityLoader.instantiate("unityContainer", "%UNITY_WEBGL_BUILD_URL%");
</script>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/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.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
</head>
<body>
<div style="height:20px; width: %UNITY_WIDTH%px; background: green;" onclick="unityInstance.SetFullscreen(1)"><b>Click here to make it full screen.</b></div>
<div id="unityContainer" style="width: %UNITY_WIDTH%px; height: %UNITY_HEIGHT%px; margin: auto"></div>
<form id="webForm" style="visibility:hidden;">
<input type="hidden" id="stringInput" name="stringInput">
<input type="hidden" id="intInput" name="intInput">
<label for="webInput">web input</label><input type="text" id="webInput" name="webInput">
<button type="submit">Submit</button>
</form>
<script>
var myForm = document.getElementById("webForm");
myForm.addEventListener('submit', function(evt) {
evt.preventDefault(); //Prevent the default form submit action
var strVal = myForm.stringInput.value;
var intVal = myForm.intInput.value;
var webVal = intInput.webInput.value;
var formData = {
"strVal" : strVal,
"intVal" : intVal,
"webVal" : webVal
};
firebase.database().ref('/formDataTree').push( formData ); // Adds the new form data to the list under formDataTree node
});
</script>
</body>
</html>
Using the apiKey, authDomain, etc in the template it means that it will show up when inspecting the page or viewing page source as. Yet, as mentioned here, it's ok to share that information.
Then, in your Assets folder, create a Plugins folder and add to it a .jslib file, for instances named form.jslib, that has a function that shows the form, and puts game data into the form's hidden inputs.
mergeInto(LibraryManager.library, {
ShowWebForm: function (importantString, importantInt) {
var myForm = document.getElementById("webForm");
myForm.stringInput.value = Pointer_stringify(importantString);
myForm.intInput.value = importantInt;
myForm.style.visibility="visible"
},
});
After the steps up to this point, if you get in the console net::ERR_BLOCKED_BY_CLIENT, simply deactivate AdBlocker for that site as that's why you get that error.
Finally, in Unity, declare that function and call it when appropriate. So, considering you have a newly created scene (so it only has Main Camera and Directional Light), you could call that method in some code that gets called in the new scene. It's a static method so as long as you can find the data you need for the parameters you can call it from anywhere.
[DllImport("__Internal")]
private static extern void ShowWebForm(string importantString, int importantInt);
public void Start()
{
// Suppose we want to send the version of unity the app is running on
// and the unix timestamp at start
string unityVersion = Application.unityVersion;
System.DateTime epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0,
System.DateTimeKind.Utc);
int cur_time = (int)(System.DateTime.UtcNow - epochStart).TotalSeconds;
ShowWebForm(unityVersion, cur_time);
}
Alternatively, if you don't want to have the user fill things out in the browser, you can leave the form invisible and instead of setting it to visible, dispatch a submit event:
mergeInto(LibraryManager.library, {
ShowWebForm: function (importantString, importantInt) {
var myForm = document.getElementById("webForm");
myForm.stringInput.value = Pointer_stringify(importantString);
myForm.intInput.value = importantInt;
myForm.webInput.value = "some other value from the game could go here";
myForm.dispatchEvent(new Event('submit'));
},
});
Can't test at the moment, so be aware of typos or other syntax errors.
I am currently first year student and I am creating web application. I have manage to redirect the page to the main menu using window.location = "".
However, I want multiple redirect pages such as admin user can access to their own page as well as the new user can go to their page and finally the employee would go to their own page.
My current functions are in js file and main codes are in HTML file. Can someone help me please?
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.location = "main.html"
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
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>Diabetes Login</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
<link rel="stylesheet" href="css/style4.css" />
</head>
<body>
<div id="login_div" class="main-div">
<h3>Welcome to Diabetes log</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>
<div id="user_div" class="loggedin-div">
<h3>Welcome User</h3>
<p id="user_para"> You're currently logged in.</p>
<button onclick="logout()">Logout</button>
</div>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBHP48kjdW-YzKCdZA_-TcVnni-NlCZZ8Q",
authDomain: "diabetesapp-ee8fa.firebaseapp.com",
databaseURL: "https://diabetesapp-ee8fa.firebaseio.com",
projectId: "diabetesapp-ee8fa",
storageBucket: "diabetesapp-ee8fa.appspot.com",
messagingSenderId: "769133104242"
};
firebase.initializeApp(config);
</script>
<script src="js/index.js"></script>
</body>
</html>
I have decided to work with Firebase instead of using SQL and PHP, which is making the backend development easier. However, I'm getting the TypeError: Cannot read property 'style' of null error for the ID element: login_div. Most of this code is from a YouTube video Firebase web login tutorial. The issue started when I attempted to move the log out button out of the index page and onto another HTML file. I decided to keep a copy on both, however, the whole page keeps constantly refreshing and going back and forth between login page and my homepage, if the line document.getElementById("login_div").style.display = "block"; is changed or removed and I don't know how to fix this. I tried changing the ID name which did nothing and tried moving the div into the homepage wich just started refreshing the whole page over and over again.
firebase.auth().onAuthStateChanged(function(user) {
//checking with firebase if there is a user
if (user) {
// User is signed in successful
//document.getElementById("user_div").style.display = "block";
document.getElementById("login_div").style.display = "none";
var user = firebase.auth().currentUser;
if (user !== null) {
//what to display if user is logged in
window.location.href = "chat.html";
}
} else {
// No user logged in displays login div hides user div
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login() {
var userEmail = document.getElementById("email_field").value;
var userPassword = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Error messages for failed login
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
});
}
function logout() {
//log out function
firebase.auth().signOut().then(function() {
window.location.href = "index.html";
});
}
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<!-- login in page and button -->
<div id="login_div" class="main-div">
<h1>The Bridge Login</h1>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password" id="password_field" />
<button onclick="login()">Log In</button>
</div>
<div id="user_div" class="loggedIn-div">
<button onclick="logout()">Logout</button>
</div>
<!-- firebase authentication server connection-->
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>
I'm just getting started with firebase and javascript html to make a website for my app.
all I'm trying to do is access any value from firebase and print it on the website.
I followed firebase's quickstart tutorial and copied the exact same code they have: https://www.youtube.com/watch?v=k1D0_wFlXgo
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript</title>
</head>
<body>
<h1 id="bigOne"></h1>
<script src="https://www.gstatic.com/firebasejs/3.3.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyD0C9hhfpdKEIahisG0VNInZZGjCyf5Lo0",
authDomain: "game-of-chats-ce897.firebaseapp.com",
databaseURL: "https://game-of-chats-ce897.firebaseio.com",
storageBucket: "game-of-chats-ce897.appspot.com",
};
firebase.initializeApp(config);
var bigOne = document.getElementById('bigOne');
var dbRef = firebase.database().ref().child('text');
dbRef.on('value', snap => bigOne.innerText) = snap.val())
</script>
</body>
</html>
am I missing something? I am new so there might be one small step that I'm missing.
Try with:
dbRef.on('value', function(snapshot) {
bigOne.innerText = snapshot.val();
});