Hi, so for the past week was learning django channels, and have succesfuly integrated it with my app, and everything works fine.
the notifications show up
the like/unlike button works as well
and also the follow/unfollow a user also works
but only thing is that on every page it connects the websocket
is there a way to only connect it once the user logs in ? and keep the connection till the user is browsing the website or is in the session.
i know i can just use the JS file only on the pages i want, but i want the notifications JS file on the base html, so the user gets live notifications no matter which page they are.
My js file (This is my like a post file)
var surfing_user = document.getElementById("user_surfing").getAttribute("value")
if (surfing_user !== "AnonymousUser") {
if(document.querySelector('.flexbox-container') !== null){
const like_unlikeSocket = new WebSocket(
'ws://' + '0.0.0.0:8000' +
'/ws/like_unlike_a_post/'
);
like_unlikeSocket.onopen = function(e) {
console.log("like_unlike_a_post WebSocket connection established!");
const container = document.querySelector('.flexbox-container');
container.addEventListener('click', function(event) {
if (event.target.matches('[name="item-id"]')) {
const retailer_id = event.target.value
const clickedBtn = document.getElementById(`like-unlike-${retailer_id}`)
// Send some data over the WebSocket
like_unlikeSocket.send(JSON.stringify({
"retailer_id": retailer_id,
}));
// GET some data over the WebSocket
like_unlikeSocket.onmessage = function(e) {
var data = JSON.parse(e.data)
clickedBtn.innerHTML = `${data.no_of_likes} <i class="fa fa-heart small-heart"></i>`
}
}
})
}
}
}