Baik berikut code script javascript yang bisa saya share
<style>
#chat-box {
border: 1px solid #ccc;
padding: 10px;
width: 100%;
height: 400px;
overflow-y: scroll;
}
.message {
margin-bottom: 10px;
}
.message .user {
font-weight: bold;
}
</style>
<h2>Realtime Chat</h2>
<div id="chat-box"></div>
<form onsubmit="handleSubmit(event)">
<input type="text" id="message-input" placeholder="Type a message" required>
<button type="submit">Send</button>
</form>
<div id="login-container">
<button id="login-button" onclick="handleLogin()">Login with Google</button>
<button id="logout-button" onclick="handleLogout()" style="display: none;">Logout</button>
</div>
<script>
// Function to display chat messages
function displayMessage(user, text) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('div');
messageElement.classList.add('message');
messageElement.innerHTML = `<span class="user">${user}:</span> ${text}`;
chatBox.insertBefore(messageElement, chatBox.firstChild); // Insert message at the beginning
}
// Function to send a new message
function sendMessage(user, text) {
// Push a new message to the 'percakapan' node with timestamp
firebase.database().ref('percakapan').push({
user: user,
text: text,
timestamp: firebase.database.ServerValue.TIMESTAMP // Add server timestamp
});
}
// Listen for new messages in the 'percakapan' node
firebase.database().ref('percakapan').orderByChild('timestamp').on('child_added', (snapshot) => {
const message = snapshot.val();
displayMessage(message.user, message.text);
});
// Handle user authentication state
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// Get all existing messages from the database and display them
firebase.database().ref('percakapan').orderByChild('timestamp').once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
const message = childSnapshot.val();
//displayMessage(message.user, message.text);
});
});
document.getElementById('login-button').style.display = 'none';
document.getElementById('logout-button').style.display = 'block';
} else {
document.getElementById('login-button').style.display = 'block';
document.getElementById('logout-button').style.display = 'none';
}
});
// Handle form submission
function handleSubmit(event) {
event.preventDefault();
const user = firebase.auth().currentUser;
if (user) {
const messageInput = document.getElementById('message-input');
const text = messageInput.value;
sendMessage(user.displayName || user.email, text);
messageInput.value = ''; // Clear the input
} else {
alert('You need to be logged in to send messages.');
}
}
// Handle login
function handleLogin() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider)
.catch((error) => {
console.error('Error logging in:', error);
alert('Failed to log in. Check console for details.');
});
}
// Handle logout
function handleLogout() {
firebase.auth().signOut();
}
</script>
Jangan lupa untuk mengubah rule di realtime firebase menjadi sebagai berikut:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
Chat akan disimpan di Realtime database dengan corsponden percakapanBerikut link yang sudah kami buat untuk melihat Chatbox tersebut klik disini
Post a Comment