ELIAS YOUSSEF
ELIAS YOUSSEF

Reputation: 79

can't change variable value javascript

So I'm working on a script that will save every second a person was online on whatsapp (on whatsapp web)

and I have this:

//add zeros (run only once)
function addZero(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

//Inject jQuery (run only once)
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

// make online log
//start
var online = "yes";
var onlineCheck1 = window.setInterval(function() {
  var x = $('#main>header>div.chat-body>div.chat-status>span').text()
  var name = $('#main>header>div.chat-body>div.chat-main>.chat-title>span').text()
  var d = new Date();
  if (x == "online") {
    var online = "yes";
    console.log(d.toLocaleDateString('en-GB') + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + name + " " + "was" + " " + "///online///");
  } else if (online == "yes") {
    console.log("<------------>")
    var online = "no";
  } else {
    var online = "no";
  }

}, 1000); //end

and it's logging when someone is online but I want it to put just one mark (<------------>) when the person is offline and it's not doing that.

so what I want this script to do is:
make the variable "online" with the value "yes"
then make the variable "x" with the value the inner text of an element (which is online or last seen.....)
and then look if x is online? then change the value of "online" to "yes" log the date and time
if not and if the value of the variable "online" is "yes"? then log a mark (<------------>) and change the value of "online" to "no"
if not? then just change the value of the variable "online" to "no" and repeat.
I don't know what is going wrong but it may be that the variables are not getting changed for some reason.

Note: i'm using chrome's console to run this script on web.whatsapp.com so you can try it if you want to see what I mean.

Upvotes: 1

Views: 3537

Answers (2)

curveball
curveball

Reputation: 4505

First off, your code looks somewhat dirty - put function out of setInterval.

Secondly, what if the Jquery script from google, injected at the beginning of the code, gets stuck and $ is not defined when you call it?

Then, use setTimeout and call it recursively instead of setInterval.

As for your variable "online" - you use "var" inside your function, so "var online" is created within your anon. function`s scope and the external "var online" is not affected by your manipulations. Try to remove "var" word inside your anon. function in setInterval.

Upvotes: 2

edshot
edshot

Reputation: 51

Try to remove the "var" keyword from the variables you want to change inside the if-else statements...

Upvotes: 1

Related Questions