How to save an option for background.html in popup? - javascript

I have a problem, what i cant solve yet. I have a popup page with a menu, and tabs, and there is a settings tab. On settings tab, i save some item to localstorage, one of them is notification_time for a desktop notification.
Note: i have no options page!
My extension has this popup window and a background page, its function is to alert user with a desktop notification. I show notification in every 5,10,30 minutes, 1,2 hours etc. And this time should be chooseable on popup pages's options menu. The problem is, if 5 minutes is saved, and when i update to 10 minutes for example, than background.html is not updating himself! I rewrited code almost 20 times, but couldnt find solution. Heres a code sample,and a printscreen to get clear about my problem.
popup:
$("#save_settings").click(function(){
var bgp = chrome.extension.getBackgroundPage();
localStorage.setItem("notifynumber",$("#notifynumber").val());
if($("#notify").attr('checked')){
localStorage.setItem('chbox','true');
} else {
localStorage.setItem('chbox','false');
}
if($("#notif_time_select :selected").val()!="default"){
bgp.setTime(parseInt($("#notif_time_select :selected").val()));
}
if($("#org_select :selected").val()!="default"){
localStorage.setItem('org',$("#org_select :selected").val().replace(/%20/g," "));
}
});
Note: save_settings is a button, on the tab there is a checkbox (if checked then notifications are allowed, else diabled). There are two html select tags, one for choosing some data (org = organisation), and one, for selecting time. "#notif_time_select" is the html select tag, where i choose 5,10,30 minutes etc...
So, whenever i click save button, i save checkbox state to localstorage,and i call one function from background page, to save time.
:bgp.setTime(parseInt($("#notif_time_select :selected").val()));
background page:
for saving time i use function setTime:
var time = 300000; // default
function setTime(time){
this.time=time;
console.log("time set to: "+this.time);
}
after, i use setInterval to show notification periodically
setInterval(function(){
howmanyOnline("notify",function(data){
if(data>localStorage.getItem("notifynumber")){
if (!window.webkitNotifications) { // check browser support
alert('Sorry , your browser does not support desktop notifications.');
}
notifyUser(data); // create the notification
}
if(localStorage.getItem('tweet')=='true'){
if(data>localStorage.getItem("notifynumber")){
sendTweet(data,localStorage.getItem('org'),localStorage.getItem('ck'),localStorage.getItem('cs'),localStorage.getItem('at'),localStorage.getItem('ats'));
}
}
});
},time);
The code inside setInterval works fine, the only problem is,that
},time);
is not updating well. If i change settings to show notifications in every 10 minutes, it stays on 5 minute. The only way is to restart the whole extension. How could i update setInterval's frequency without restarting the whole extension? Thanks Jim
What if i save notif_time to localStorage too, and in background, i set up a listener, to listen for localStorage changes. Is there a way to listen for a particular localStorage item changes?!

Right now, setInterval only runs once, when your application loads. If you want intervals to fire at a new time interval, you should use clearInterval and then make a new call to setInterval.
// set a new time, wipe out the old interval, and set a new interval
function setTime(t) {
window.time = t;
clearInterval(notifInterval);
notifInterval = setInterval(makeNotification, time);
}
// set first interval
notifInterval = setInterval(makeNotification, time);
function makeNotification() {
// do what you need to make a notification
}
Here, notifInterval is a reference to the interval, returned by setInterval, that is used to clear it.

The source code in your question is not completed, but I guess you called setInterval() and then modified window.time in the background page.
Your window.time is not an object but a number value, and setInterval() can't "see" changes of window.time after invocation.
Try this:
function onTimeout() {
// do your notification.
setTimeout(onTimeout, time);
}
setTimeout(onTimeout, time);

Related

How can I click 2 buttons simultaneously?

I work in a Call center (ticket based Support) and for me to get a ticket I need to click on 2 Buttons. the one that opens the tickets section, and the one that actually gets me a ticket. After i click on the Get_ticket class, the ticket box closes. So i need to start again to click on the "Tickets" Button, and then on Get_Ticket. Tickets button -> Get_ticket. And repeat and repeat. I want to tell Google console to help me with this. I found a way but it's not very friendly. I tried with the button.click function at a different interval but it's not working...If i put the function separately, it's working, but when I put the functions at the same time in Console, it's not working. Can you please give me an advice ? Those are the functions:
1.(click on TICKETS)
var button = document.getElementsByClassName("_1f8o8ru7")[0];
setInterval(function(){button.click();},2000);
2.(Click on GET TICKET)
var button2 = document.getElementsByClassName("_sl2x43m")[0];
setInterval(function(){button2.click();},2500);
The second interval should be added inside the first interval. I also recommend to use setTimeout, instead of setInterval.
setInterval(function(){
var button = document.getElementsByClassName("_1f8o8ru7")[0];
button.click();
setInterval(
function(){
var button2 = document.getElementsByClassName("_sl2x43m")[0];
button2.click();
},2500);
},2000);
After you figure it out, you can save your code in a js file: my_script.js and use Chrome extension JS Injector to automatically inject it in your page, without needing to use Chrome DEV Tools.
you need to call first button click on click of first button call another method on given timeout
so first time 1 button is clicked after on click of first button call another button method with 500 timeouts will be ok no need to do 2000 or 2500 timeout

Countdown time when tab is out of focus

I'm trying to calculate time when user is out of current tab.
if user is changes tab for more than 3 times, page should navigate to another page. OR if user changes tab for more than 10 seconds, page should navigate to another page.
So far i got this only:
$(window).blur(function() {
alert("You are navigating to other tabs or window. this is your first warning. Doing this again may cancel your current examination.");
});
i need something like this:
if (user changes tab){
//display warning
}
if(user changes tab for more than 3 times){
//navigate to another page
}
if(user changes tab for more than 10 seconds){
//navigate to another page
}
Answer originally came from: https://stackoverflow.com/a/1760268/680578
His code snippet can be found here: http://jsfiddle.net/meehanman/40edh944/
You are able to keep track of active/inactive tabs using jQuery's focus and blur. You should be able to use a global variable to keep track of the amount of times the user did not have their focus on your tab. Displaying your warning at the first time, and your second warning after 3 times.
Whether it has been 10 seconds can be done using a setInterval countdown for example. Which you can clear as soon as your user comes back to your tab.
var counter = 0;
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});

Changing link URL after every 5 visits

What I'm trying to accomplish is the following.
I have a link on my website, however I want to change that link after every 5 visits or "page refreshes" by the user and have this loop.
So for example you visit my site and the download button links to a site called "www.site1.com". You refresh my site 5 times and the download button link changes to "www.site2.com". If you refresh it for a 6th time it goes back to the original.
I have not been able to find anything searching through forums that shows what i'm trying to accomplish here. I was just experimenting with a window.onload and setInterval function that changes the link every 5 seconds. Anyway to easily transition this from every 5 seconds to every 5 page visits?
window.onload = function() {
function changeURL(){
document.getElementById("link").href = "www.site1.com";
}
setInterval(changeURL, 5000);
}
You probably want to use JavaScript localStorage or sessionStorage for this. Below is an example of your code using localStorage
Example
window.onload = function()
{
if (localStorage.visits)
{
//If the value is in local storage increase it's value
localStorage.visits = Number(localStorage.visits) + 1;
}
else
{
//If the value isn't in local storage set it to 0
localStorage.visits = 0;
}
//Check if the number of visits is greater than 5 and set the link accordingly
if(localStorage.visits > 5)
{
document.getElementById("link").href = "www.site2.com";
}
else
{
document.getElementById("link").href = "www.site1.com";
}
}
This will only work if their browser supports localStorage. One thing to note as well, the value will not reset if they close the browser page. If you want it to reset when the page is closed, that's what sessionStorage is for.
One more thing to note: The user can clear localStorage by clearing the browser data. If you wanted something that would be even more persistent I don't believe there's a JavaScript only solution (feel free to correct me if I'm wrong about this!)

How to reset jquery dialog timeout for next dialog?

I have an add-to-bag button used throughout our site and we want a dynamic popup to appear to acknowledge what was just added, and then it goes away. I'm finding that if you click another add button, it has the previous dialog's timeout attached. To fix this so the next dialog has its own 10,000 setTimeout rather than whatever is left over from the last one I have come up with the following code (that doesn't do the trick).
$(document).ready(function ()
{
// Create object for future dialog box - so it's available to the close method
var addToBagDialogVar = $('<div id="addToBagDialogBox"></div>');
var autoCloseTimeout = 10000;
var dialogTimer;
$(".addToBagPU").click(function (e)
{
var result = "";
$.get(this.href, function (data) { SetData(addToBagDialogVar, data); });
return false;
});
// Start listening for the close link click
$(document).on("click", "#bagPUCloseLink", function (event)
{
event.preventDefault();
CloseDialog(addToBagDialogVar);
});
function SetData(addToBagDialogVar, data)
{
result = data;
var regex = data.match("{{(.*)}}");
var bagCount = regex[1];
addToBagDialogVar.html(result).dialog({
open: function ()
{
clearTimeout(dialogTimer);
$(".ui-dialog-titlebar-close").hide();
SetBagCount(bagCount),
dialogTimer = setTimeout(function () { CloseDialog(addToBagDialogVar); }, autoCloseTimeout);
},
show: { effect: "fadeIn", duration: 800 },
close: function () { clearTimeout(dialogTimer); },
width: 320
});
}
function CloseDialog(closeThisDialog)
{
closeThisDialog.dialog("close");
closeThisDialog.dialog("destroy").remove();
}
});
The dialog is loaded with dynamic content from an external .Net page with product data and has a close link inside that page, which is why the dialog is loaded into addToBagDialogVar so it's available to CloseDialog.
All of that works just fine. It's just the reset of the timer that doesn't appear to be happening. If I go down a page of products and add each one to my bag, the 3rd or 4th dialog is only up for a second or so because they have all been using the first dialogs setTimeout.
I've read and read and tried too many different ways to remember and now my brain is mush.
I propose an alternate explanation for the behavior you're observing. When you click the first "add to cart", a timer is started. As you go down the page clicking "add to cart", a new timer is started each time. There's no overlap, just a bunch of separate timers running normally (although incidentally, each new dialog box blows away the timer ID you've previously created; I'll come back to this).
When your first dialog's timer expires, the dialog closes itself via the HTML ID, meaning it closes itself with something like a jquery $('div#addToBagDialogBox').closeOrSomethingLikeThat(), that is, every dialog inside a div with an id of addToBagDialogBox. The first timer expiration is closing all of your dialogs, because they all use that same HTML ID. The other timers are running perfectly, but when they expire there's nothing left for them to do.
You can fix the early-close problem by assigning a unique HTML ID to each dialog you create. And you'll want to manage your timer IDs on a per-dialog basis as well, such that each dialog has its own timer ID.
Edit: Just for nerdy grins, think about the details of the scenario you described. Your first timer is running, counting down normally, and you start four other timers while the first dialog is still there. The ID of the fifth timer is in your variable dialogTimer. So when the first dialog's timer expires, the close processing occurs, and you call clearTimeout with the ID of the fifth dialog's timer. So your first dialog's timer expired, the dialog closed all the other dialogs, and the cleanup cancelled the fifth timer. There are three other timers still running, their IDs lost forever. They finally expire and their shutdown functions run, but they're totally without effect, their companion dialogs long gone. Sorry, bona fide nerd here.

How do I make a pop-up that only appears after the visitor has been on the page for a certain amount of time?

I am trying to add a non-intrusive 'Sign up to our newsletter' pop-up to a website I have been working on, but would like the pop-up to only appear after the user has been on the website for longer than 3 minutes or so. If anyone can help me achieve this that would be great.
Thanks in advance everybody
Right, so there are a couple things to consider. Your popup display attribute, the function that will show your popup, and the amount of time that needs to pass before your function fires.
<style>
.SignupPopup{display:none}
</style>
<!-- Page HTML -->
<div id="SignupPopup" class="SignupPopup"></div>
<script>
// Function that displays your popup
function popSignupForm(){
document.getElementById('SignupPopup').style.display = 'block';
}
// Using setTimeout to fire the popSignupForm function
// in 3 minutes time (this is done in milliseconds)
setTimeout( function(){
popSignupForm();
}, 180000 );
</script>
That will work so long as the user stays on the same page for 3 minutes. If you want the the popup to appear after 3 minutes on your site, you need to create a cookie and timestamp it when the user first arrives at your site. You can then measure the elapsed seconds (from the timestamp) every x intervals to see if its time to popup your newsletter signup form.
The pseudo will look something like this:
function onPageLoad(){
If Cookie Doesn't exist for your site
Create Cookie
Record Timestamp
//Start Checking the cookie to see if
//it's time to show the popup
checkCookieTime()
}
function checkCookieTime(){
// Check to see if at least 3 minutes
// Have elapsed from the time of the cookie's
// cookie's creation
If Now is >= (Cookie.TimeStamp + 3 minutes )
popSignupForm()
Else
// Check again in 10 Seconds
setTimeout( function(){
checkCookieTime()
}, 10000 );
}
Here's a good article from quirksmode on reading/writing cookies.
You can use settimeoutfunction in javascript
setTimeout(function(){},time);

Categories

Resources