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.
With the help of a realtime firebase database and some arduino code, I am displaying Moisture levels of potting soil on my website. However when the firebase data is updated (every 0.3 seconds), instead of also updating the single value on the website, it adds a new line/print every update. After a short while, my website now looks like this:
Moisture: 661Moisture: 658Moisture: 660Moisture: 658Moisture: 657, and it keeps on adding the Moisture: xxx after it with every update. What I want to happen is to just have it displayed once, and push the data so it updates the first value, rather than adding a new one.
I'll leave my code below, how can I go about doing this? It's hard to find things about this on the internet as I am not sure what I am looking for (new to JS).
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
</script>
<script>
var database = firebase.database();
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "plant-patrol"
var childKey = snapshot.child().key; // "Moisture"
});
</script>
<script>
var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
console.log(snapshot.val());
var snapshotJSON = JSON.stringify(snapshot.val());
var moisture = snapshotJSON;
moisture = moisture.replace(/[{""}]/g, '');
moisture = moisture.replace(/[:]/g, ': ');
document.write(moisture);
}, function (error) {
console.log("Error: " + error.code);
});
</script>
<script src="/script.js" defer></script>
</head>
</html>
var div = document.getElementById('moisture');
div.innerHTML = 'Moisture: 55%';
<div id='moisture'></div>
Your are using document.write(moisture). This writes the moisture variable on the document each time is received.
What you want is to replace a specific text in the document. To do that you must create an element with an unique ID like:
<div id='moisture'></div>
First, assing that element to a variable:
var moistureDiv = document.getElementById('moisture');
Then, remove the document.write(moisture) and add this code to replace the text on the element with "moisture" ID:
moistureDiv.innerHTML = moisture;
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();
});