How can I check if a referring domain is blank? - javascript

I've written a bit of JavaScript that reads the referring URL of a page and loops through an object to check for strings such as "google", "msn", "bing" etc. The resulting value is stored in a variable which is then passed to a server. Now this all works perfectly but my question is around detecting traffic directly to a site (i.e. people typing the URL in the address bar). How can I detect this?
I was thinking, that I could do something like:
var refURL = document.referrer;
var serverVar = "";
if (refURL === "") {
serverVar = 'direct traffic';
}
Should I be checking for "" (i.e. blank) or should I be checking if refURL is null?

If you dont want to do the way you are comparing now as in your code, You could use:
//check for blank, null or undefined
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var refURL = document.referrer;
var serverVar = "";
if (isBlank(refURL)) {
serverVar = 'direct traffic';
}
Hope it helps

Just use if(!document.referrer) {}

Related

How to find a Integer variable by its value using a debugger?

is there a way to find all variables with a specific value in JS?
I know there is a variable holding value integer 374646 but I can not find it in sources (large codebase).
I think one can implement a solution by recursively checking all variables returned by this but I am not a JS developer
update:
the original question was confusing I think.
is there any way that I can find variables by values in a browser debugger (Chrome/Firefox)?
I think one can implement a solution by recursively checking all variables returned by this but I am not a JS developer
No, you can't. Properties are not variables (except in one special case: a certain class of global variables are properties of the global object).
Unless your variable is a global, and it's the kind of global that's available as a property on the global object, you can't find it. There is no way to get a list of other kinds of variables.
For example, there is no way for code at global scope to find a in the following:
const handle = (() => {
const a = 374646;
return setInterval(() => {
console.log(a);
}, 500);
})();
setTimeout(() => clearInterval(handle), 4000);
Please note that it's dangerous and do not access the sites, that you don't know with that approach!!! All your data may get stolen, your girlfriend may get r#$%ped, your grandma may die, your dog may bite you in the crotch, all the glaciers in the world may melt, you can get herpes or even start a global nuclear war! Use at own risk! A very high risk if you don't know what running a browser without cross-domain policies means!
Run your browser with cross-domain policies disabled (for example Chromium / Chrome with --disable-web-security param, note : Kill all chrome instances before running command or it won't work), then in the console copy-paste this function:
function globalSearch(startObject, value) {
var stack = [[startObject,'']];
var searched = [];
var found = false;
var isArray = function(test) {
return Object.prototype.toString.call( test ) === '[object Array]';
}
while(stack.length) {
var fromStack = stack.pop();
var obj = fromStack[0];
var address = fromStack[1];
if( typeof obj == typeof value && obj == value) {
var found = address;
break;
}else if(typeof obj == "object" && searched.indexOf(obj) == -1){
if ( isArray(obj) ) {
var prefix = '[';
var postfix = ']';
}else {
var prefix = '.';
var postfix = '';
}
for( i in obj ) {
stack.push( [ obj[i], address + prefix + i + postfix ] );
}
searched.push(obj);
}
}
return found == '' ? true : found;
}
After that you can search variable by values with:
globalSearch(window,value);
Once again! Remember that it's dangerous and do not access the sites, that you don't know with that approach!!! Disclaimer: If something will happen, you didn't even see that post, I didn't write it! I don't know what StackOverflow is! Never been here.

Problem with string: "undefined", unable to check this case [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm getting coordinates via an API that works most of the time
(giving me a String with a double, example : "53.2") but sometimes i see in the javascript console that I receive 'undefined' instead of let's say 53.2.
I tried to check if what i receive is undefined but it doesn't work and I keep getting this type of error sometimes:
"java.lang.NumberFormatException: For input string: "undefined" "
Could you help me please? I'd like to know if I have to check with another condition, maybe null or something else..
EDIT: My main concern is more to know when i get undefined value in the Java servlet and less to make the Javascript work better. Thank you!
//JAVA CODE IN THE SERVLET
String fromlong = request.getParameter("fromlong"); //COORDINATES
String fromlat = request.getParameter("fromlat");
String tolong = request.getParameter("tolong");
String tolat = request.getParameter("tolat");
if(fromlat == "undefined") {
fromlat = "50.0";
}
if(fromlong == "undefined") {
fromlong = "50.0";
}
if(tolat == "undefined") {
tolat = "50.0";
}
if(fromlat == "undefined") {
tolong = "50.0";
}
//Then there is a function that uses these values
and that's the javascript code where i get the values with an api then send them with a hidden input (this works when the api sends me a correct value most of the time then i'd like to check if what i got in the servlet is correct before using it)
getCoordinates1(from);
function getCoordinates1(database){
$.ajax({
url: 'http://api.positionstack.com/v1/forward',
data: {
access_key: 'MYKEY',
query: database,
limit: 1
}
}).done(function(data) {
var mylatitude = data.data[0].latitude;
var mylongitude = data.data[0].longitude;
document.getElementById('fromlat').value = mylatitude;
document.getElementById('fromlong').value = mylongitude;
console.log(data.data[0].latitude);
console.log(data.data[0].longitude);
});
}
and at the end of the page i send this with an hidden input
<input type="hidden" id="fromlat" name="fromlat" value="" />
You have to compare strings with .equals()
You are comparing them with "==".
If you do like you did, you are comparing the object reference, not the actual value of the string.
Which evaluates as false every time since it is not the same object.
if (fromLat.equals("undefined")) { ...
Edit:
You also have a logical error in your code:
if (fromlat == "undefined") {
tolong = "50.0";
}
should be:
if (tolong.equals("undefined")) {
tolong = "50.0";
}

isNaN not working JavaScript

I’m having trouble with the isNaN function is JavaScript. I have a variable, trc, which I know is not a number, but I want my code to be able to tell. Unfortunately, isNaN isn’t detecting that it’s not a number, yet when I use an alert to show the value of the variable, it is indeed not a number.
trc = parseInt(getCookie("trc"));
cnn = parseInt(getCookie("cnn"));
klove = parseInt(getCookie("klove"));
if (isNaN(trc)) {
trc = 0;
}
if (getCookie("trc") == undefined) {
trc = 0;
} else {
trc = parseInt(getCookie("trc"));
}
alert(trc);
BTW, I have a separate function, getCookie(), that I made myself to get the value of a cookie.
You should check value of trc before.
If trc is null, then isNaN(null) return false.
Edit:
parseInt method doesn't return null value, but trc can be modified by external code - therefore I recommend using namespaces e.g:
var namespace = namespace || {};
namespace.trc = .....

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

Greasemonkey testing if array element exists

I'm writing a script that adds labels to things on a page using an element from an array based on part of the link... so my array looks like this:
var componentList[9] = "Sunnyseed"
var componentList[10] = "Echoberry"
var componentList[11] = "Riverstone"
var componentList[13] = "Auraglass"
var componentList[14] = "Skypollen"
You'll notice there is no '12'... I want the label to be 'Unknown' when the array item doesn't exist. Now, I can't exactly test my solution since I can't cause the target page to throw me a 12... so I was hoping somebody would tell me whether this will do what I want or not...
var component = ""
if(typeof componentList[critterIDval] == 'undefined'){
component="Unknown"
}
else{
component=componentList[critterIDval]
}
This is obviously not the full script, but it should be the important stuff... I just want to know if that will make it say 'Unknown' when the critterIDval is 12 - since it could take years to come across the situation for testing.
You're pretty much there. You're using a single-equals sign in your comparison, so that will mess it up, and I'm not sure you can create a JS array like that, but aside from that, you're good.
Here is the test I ran for it:
var componentList = [];
componentList[9] = "Sunnyseed";
componentList[10] = "Echoberry";
componentList[11] = "Riverstone";
componentList[13] = "Auraglass";
componentList[14] = "Skypollen";
for (var critterIDval = 9; critterIDval < 15; critterIDval++) {
if (typeof componentList[critterIDval] == 'undefined') { // double equals here
component = "Unknown";
} else {
component = componentList[critterIDval];
}
console.log(component);
}
It looks fine.
Though if you are sure that the value will never be an empty string(like componentList[14] = '';) then you can try
var component = componentList[critterIDval] || 'Unknown'
I want the label to be 'Unknown' when the array item doesn't exist.
The typeof operator does not tell you if a property exists or not as it returns undefined when the property doesn't exist but also when it does exist and has been assigned a the value undefined or simply created but hasn't been assigned a value.
There are two primary ways to test for the existence of a property: the in operator, which also looks on the [[Prototype]] chain and the hasOwnProperty method of all Objects. So
if (componentList.hasOwnProperty(critterIDval)) {
component = "Unknown"
} else {
component = componentList[critterIDval]
}
which you could also write as:
component = componentList.hasOwnProperty(critterIDval)? componentList[critterIDval] : 'unknown';
PS. there are other methods, such as looking at Object.keys(componentList) and componentList.propertyIsEnumerable(critterIDval), but the above are the most common.
Edit
If your requirement is not just to test for property existence but to also test for a "truthy" value, then:
if (componentList[critterIDval])
may be sufficient and will return false where the value is '' (empty string), 0, false, NaN, undefined or null.
Maybe just testing for a non–empty string or number will do:
if (/.+/.test(componentList[critterIDval]))
but that returns true for NaN, null and so on. So you need to specify what you are actually testing for, otherwise you may get undesired results for some values.

Categories

Resources