Chrome extension - Background page and unread items - javascript

I'm making my first chrome extension and i'm stuck just before the end.
I'm getting a response from a server in json, outputing the html, cache it in localstorage check if there's cache if not getting again from server and then displaying.
Now. In the background.js I need to check every 30 mins if there're updates in the json file on the server... if any display a Badge, once clicked remove badge till next time. but I don't know what to do. Because if I make a setInterval it hits the server and always display a badge even if there's nothing new. Can you guy help me build the js, please?
<script>
setInterval(function(){
chrome.browserAction.setBadgeText({text:chrome.browserAction.setBadgeText({text: "!!!"});});
}, 1800000);
</script>
I've also tried this way, but nothing happens.
function getUnreadItems(callback) {
$.ajax(..., function(data) {
process(data);
callback(data);
});
}
function updateBadge() {
getUnreadItems(function(data) {
chrome.browserAction.setBadgeText({text:data.unreadItems});
});
}
var pollInterval = 1*60*60; // 60 min
var timerId;
function startRequest() {
updateBadge();
timerId = window.setTimeout(startRequest, pollInterval);
}
function stopRequest() {
window.clearTimeout(timerId);
}
background.js
onload='startRequest()'

It looks like you never reset the unread items to "read" on the server, so every time you will ping the server, it will reply with the same number and will thus display that number again.
So you can do a couple of things:
when you click your button and reset the badge to 0, you can send a request to the server to mark all the items as read. Which request will of course depend on your server and what it accepts. That way, the unread count on the server will always be up to date and your extension can be very "stupid": whatever is returned by the server is the current number of unread items.
if you can't do that, you'll have to save some information locally to your extension and figure out the unread count yourself. What I mean by that is that instead of just requesting the unread count you'll need to get information about the specific items like a unique ID. Then every time you poll the server for the list of items, you add the IDs to a list saved in localStorage for example (or chrome.storage.sync) with a viewed tag set to false if that ID is not known yet. The background script will then go through that list and count the number of items that have a viewed tag set to false and use that as an unread count. Whenever you open the popup, you go through your whole list and set the viewed tag to true for all your items.
I've done something similar for an extension to get your Hulu playlist. I did the first option when I delete a video from your playlist, so that it's removed locally and on the server as well. And I did the second option because I wanted to show a count for new videos, but Hulu doesn't keep track of that. (it knows played and unplayed, but not "you've been notified that this new video is available" which I wanted.
See in particular, this section:
// Testing that it's the first time I'm seeing this show
if (show_ids.indexOf(new_show.id) == -1) {
new_shows_number++;
new_show.seen = "no";
} else {
new_show.seen = "yes";
}
Here show_ids is the list of IDs I've already saved and marked as viewed locally. If new_show.id is not in this list, that means it's an unviewed item.

Related

Run different js on each user visit

I want to load javascript functions on a wordpress site based on user visit, if it's the first time, then one function will run, if its second visit another code will run., I found that using cookies and local storage we can set it, but only track user if visited or not., I want to count the user visit, and based on that run the functions.
var first_visit = false;
checkFirstVisit();
function checkFirstVisit(){
if(localStorage.getItem('was_visited')){
return;
}
first_visit = true;
localStorage.setItem('was_visited', 1);
}
console.log(first_visit);
this code is to track the first visit, How do I make it to track the number of visits?
You can use session storage in PHP (https://www.w3schools.com/php/php_sessions.asp) to store in a variable whether this is the user's first visit or not.
Then using an if-else statement, display the required code.
The good thing about PHP session storage is that it can retain the storage even after the user closes the browser.
it is the same thing
set a cookie for visiting
if it is not set so it is the first visit so set it to 1
if it is 1 so second visit so set it to 2
if it is n so it is n + 1 visit so incrment n

odoo notification if the record data is out of date

when odoo 15 was released I have seen this record is not up to date (not sure of the actual words)
The issue is that I have a approval for a record but if the user that summered the record for approval is still on the page he don't see the updates to the record after the approval. I do send the notification but the user wants the page to refresh or show that the record view is not up to date like (what odoo was doing in the first week of the released)
sorry is there is no code but am not sure how go about doing this.
Not expecting a solution just ideas on what you thing and maybe in you have time why your idea may fail (drawbacks).
/**
* Displays one notification on user's screen when assets have changed
*/
function displayBundleChangedNotification() {
if (!isNotificationDisplayed) {
// Wrap the notification inside a delay.
// The server may be overwhelmed with recomputing assets
// We wait until things settle down
browser.clearTimeout(bundleNotifTimerID);
bundleNotifTimerID = browser.setTimeout(() => {
notification.add(
env._t("The page appears to be out of date."),
{
title: env._t("Refresh"),
type: "warning",
sticky: true,
buttons: [
{
name: env._t("Refresh"),
primary: true,
onClick: () => {
browser.location.reload();
},
},
],
onClose: () => {
isNotificationDisplayed = false;
},
}
);
isNotificationDisplayed = true;
}, getBundleNotificationDelay());
}
}
addons/bus/static/src/js/services/assets_watchdog_service.js
this maybe semlar to what I need but assets
The main question here Is how to know if a user is on the modified record and run a function
setup a web socket that listens for update events identified
by ID’s and prompt notifications if the documentId of the
notification matches the ID of document on page at that point in
time.
Poll every x seconds for the record corresponding to document on page and compare some unique value that would have changed like lastUpdated. If changed prompt notification and refresh.
Keep a metadata list of open pages. Can use heartbeat interval and onLoad onUnload events to keep list valid. Whenever two or more documents are open at the same time make it known on page that “document is being edited and cannot be currently edited will update accordingly” or something like that.
Use service workers and the push api to send updates to the main running app

How to create global constant or variable whose value dont get reset after closing the app in reactjs [duplicate]

I'm trying to make a page on my tumblr that has a button on it, which counts how many times it's been pressed. I've gotten it to work, but a browser close or refresh clears the value, and clicks from different people don't stack. Here's what I have:
<body>
<div class="main">
<h3>Click Counter</h3>
<button id="clickme">Click me: 0</button>
<h5>Filler Text</h5>
</div>
<script>
var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
</script>
</body>
This makes the button count up when pressed, but I want it to behave like so:
User #1 clicks twice. Counter reads two.
User #2 visits the page, counter is already at two, user clicks 3 times. Counter is at 5.
User #3 visits, counter is still at 5 for them as well, etc.
As of right now, each user visits the page and the value starts at zero. Help?
Depending on your needs, you could use localStorage.
count = localStorage.getItem('count');
count = parseInt(count); // because localstorage stores everything in strings
// First time the value does not exist...
if(count == null) {
count = 0;
}
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
localStorage.setItem("count", count);
};
This is not a server side solution. It's also less reliable as it can be cleared by the user anytime.
javascript runs on the browser and store all the variable in the browser so the scope of a variable is in the browser. you can use local storage but if all user uses the same browser which is not your need so only way to persist data is to save count (data) into the server and fetch count (data) on a load of the page.
you can use firebase real-time database if you don't have any server.
Getting started with Firebase real-time database for the web
As I have understant form your question you want to retain the user click count, there is 3 scenerio
User visits form Single machine Single browser (rare situation)
in this you can use local storage
User visits form Single machine multiple browser
In this case you have to save it in server side
User visits form multiple machine multiple browser
In this case you have to save it in server side
Both case 2,3 are same , you need to save it in server.
A common way to do this , put you counter in db and an REST end point and call that endpoint on page each page load to take the counter form the server and also after clicking update on the server by similar end point
Suggesting learning: Client side : AJAX (Jquery) , Server side : REST API , DB (MySql,ets)

Web Notifications API - Only show once per period

I'm writing a web app that needs to send notifications. It checks 12 different things every 30 seconds and if one of them meets the criteria it should send a notification; it then shouldn't send another notification until the next 30 minute (on the hour and half past the hour) interval. How do you check if a notification has already been sent and not to send it again? I thought this was done via tags but two notifications with the same tag will still pop-up, the second will just replace the first.
The function used to generate the notification is
function randomNotification(whoisit, tagtoPass) {
var message = whoisit + " is getting a notification";
var options = {
body: message,
icon: 'logo.png',
tag: tagtoPass,
}
var n = new Notification('Website Says:',options);
setTimeout(n.close.bind(n), 5000);
}
That function is called from another script that is loaded via Ajax every 30 seconds. That script checks the database to see if one of the 12 things is in a state that requires a notifications then calls the function and passes the name and a unique tag for that 30 minute interval.
Also I've noticed with this code, which was based on the developer docs from Mozilla on Notifications API, doesn't add the notification to the OS X Notification Centre.
Have you considered using a flag in localStorage to store the time when the last notification was sent?
Let's say that you store the time when you send the first notification, then check it again and if it's old enough you send another one and update that flag.
localStorage data will stay even if you refresh the web page.
Example:
localStorage.setItem("last_notification", timestamp)
localStorage.getItem("last_notification")
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Counter Box, Visible for all clients

Hello I need a button for my website, that will start a countdown from 60 secounds to 0, then it should display some text (lets drink, cheers) and go back to start button.
All users must be able to see this countdown, so that when a user start the countdown other users can see this.
It should also display a counter, of howmany user have clicked the button, and joining in on the "button"
I have looked into this, but i need to do Ajax / javascript pulling.
Since my programming skill is still on copy/paste/edit level, I do not know howto get started, I can build the timer, but dont know howto do the pulling.
can anyone help me get started.
Regards
René
Well first of all, you need a stateful backend, to store a usercount. So php+any db.
you mentioned socket.io, build on nodejs.
With nodejs this aint this difficult, because its a single threaded runtime, so you can share variable values to different clients.
your nodejs have to listen to 3 urls:
for passing the basing page ( can be done without nodejs, just url to html)
ajax url for passing clicks on a button from client to backend, returns current count
ajax url to pass the current seconds, returns current count and connected users.
everytime the 2. channels gets called, you need to check , if the countdown is alrdy running. if not: start it, else increase clicked counter.
like this:
//nodejs code
var currendSeconds=60;
var connectedClients = 0;
var threadid;
function clientClickedButton(req, res){ // 2. url
if(currendSeconds==60 || ) {
threadid = setInterval(function(){
currendSeconds--;
if(currentSeconds == 0){
clearInterval(threadid);
}
}, 1000); //your counter
}
connectedClients++;
res.send(currendSeconds);
}
your clientside have to listen to click event on the button, send a ajax req to 2.url and display the returned seconds ( from now on our dont need to request the seconds, just set up a count down clientside, without requesting the current seconds. )

Categories