I'm currently developing a Chrome extension that is supposed to scrape my Internet activity. So first of all here is my JS code (I only have this file without counting the manifest.json, the jquery.js and the logo) :
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes
}
chrome.tabs.onUpdated.addListener(function (tabId, info) {
if(info.status === 'complete') {
chrome.tabs.executeScript({
code: "document.documentElement.outerHTML"
}, function(result) {
if (!chrome.runtime.lastError) {
var el = document.createElement( 'html' );
el.innerHTML = result[0];
var scraping = [
{
"url": "",
"title": "",
"text": "",
"ranking_word": {},
"a": [],
"img": [],
"html": ""
}
]
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
scraping[0]["url"]= tabs[0].url;
});
var head = el.getElementsByTagName('head');
for (var i = 0; i < head.length; i++) {
scraping[0]["title"] = head[i].getElementsByTagName('title')[0].innerHTML;
}
var a = el.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
scraping[0]["a"].push(a[i].href);
}
var img = el.getElementsByTagName('img');
for (var i = 0; i < img.length; i++) {
scraping[0]["img"].push(img[i].src);
}
var txt = "";
var text_in_body = [];
var body = el.getElementsByTagName('body');
for (var i = 0; i < body.length; i++){txt += body[i].textContent;}
txt = txt.split("\n");
for (var i = 0; i < txt.length; i++){txt[i] = txt[i].split(" ")}
for (var i = 0; i < txt.length; i++) {for (var a = 0; a < txt.length; a++){if (txt[i][a] == " " || txt[i][a] == "" || txt[i][a] == "," || txt[i][a] == "." || txt[i][a] == "!" || txt[i][a] == "?" || txt[i][a] == ";"){delete txt[i][a];}}}
for (var i = 0; i < txt.length; i++) {text_in_body = text_in_body.concat(txt[i])}
scraping[0]["text"] = text_in_body.join(" ");
ranking_word = {}
for (var i = 0; i < text_in_body.length; i++) {
ranking_word[text_in_body[i]] = getAllIndexes(text_in_body, text_in_body[i]).length;
}
scraping[0]["ranking_word"] = ranking_word;
scraping[0]["html"] = result;
var response = $.get("https://api.myjson.com/bins/1e0ybo", function(data, textStatus, jqXHR) {
if (textStatus == "success") {
console.log("%cSuccess: Getting Data", 'background-color: #8cc2e6; color: #000');
console.log(response.responseJSON);
console.log(scraping);
var newJSON = Object.assign(response.responseJSON, scraping);
console.log(newJSON)
$.ajax({
url:"https://api.myjson.com/bins/1e0ybo",
type:"PUT",
data:JSON.stringify(newJSON),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data, textStatus, jqXHR){
console.log("%cSuccess: Uploading Data", 'background-color: #8cc2e6; color: #000')
}
});
}
});
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
On lines 72, 73 and 75 I put console.log() to check that all variables had the values they should have, except that it's not the case (as you can see on the console screenshot below) .
I don't understand why my response.responseJSON value (I also tried with data but it gave me the same thing) and my scraping variable are equal, they shouldn't be. I checked that my file where I get the data didn't have those values but no...
Anyone have any idea how to fix this?
The screenshot
Related
How can I get the first pair of key value from ajax returned json?
Like in console, if I input response[0] to get testdaa101.com ?
.ajax({
url: "/fetch_bar",
type: "post",
dataType: "json",
async: true,
success: function(response) {#
response = {
testdaa101.com: "30",
testbb101.com: "50"
}
var len = Object.keys(response).length;
var selects = document.querySelectorAll("select[id=select_host]");
if (len == 1) {
for (var index = 0; index < selects.length; index++)
if (selects[index].value == response[0])
alert("hello")
else if (len > 1) {
for (var ind = 0; ind < len; ind++) {
for (var index = 0; index < selects.length; index++)
if (selects[index].value == response[ind]) {
alert("nice")
}
// if (response[0]){ alert
You can use Object.keys to get keys, and then take the first:
const fakeAjax = () => new Promise((res) => {
setTimeout(() => res({
first: 1,
second: 2
}))
})
fakeAjax().then(data => {
console.dir(Object.keys(data)[0]);
})
function getFirstPair(response) {
var keyValuePairs = Object.entries(response);
if (keyValuePairs.length) return { [keyValuePairs[0][0]]: keyValuePairs[0][1] };
return {};
}
getFirstPair({
"testdaa101.com": "30",
"testbb101.com": "50"
})
This would return {testdaa101.com: "30"}. But the order of key value pairs in a JSON object is not consistent. So be cautious on that point
can anyone help me please? So I'm making a web app where a user can crack the vault code by clicking the numbers from 1-40. They are only allowed to click 6 sets of numbers for example "6", "20", "1", "40", "27", "15". So I have a data variable "guess" in my database with int(12) as the var numbers in this JS below. The problem is whenever I try "40", "39", "38", "37", "36", "35". The database will catch "2147483647" and I'm getting confused why, there must be something wrong in what I'm doing. I'm not really professional with JS and I'm just following some guides. This was working when I had the 0-9 numbers in the vault and int(6) in the data var "guess" inside the database. Please help, thank you!
var numbers = document.querySelectorAll('.number');
var screenSpans = document.querySelectorAll('#screen span');
var clear = document.getElementById('clear');
var enter = document.getElementById('enter');
var errorModal = document.getElementById('digitAmountAlert');
var currEmail = document.getElementById('currEmail').innerHTML.replace(/\s/g, '');
var lastModal = document.getElementById('lastModal');
var main = document.getElementById('main');
var guess = '';
var reset;
clear.addEventListener('click', function(){
reset = 0;
for (var i = screenSpans.length - 1; i >= 0; i--) {
if (screenSpans[i].innerHTML != '' && reset == 0){
screenSpans[i].innerHTML = '';
reset = 1;
}
};
});
enter.addEventListener('click', function(){
reset = 0;
for (var i = 0; i < screenSpans.length; i++) {
// Catch if they have not entered enough digits
if (screenSpans[i].innerHTML == ''){
errorModal.className = 'modal';
setTimeout(function(){
errorModal.className = 'modal hide';
}, 4000);
} else {
guess = guess+screenSpans[i].innerHTML;
if (guess.length == 12){
$.ajax({
url: "submit.php",
method: "POST",
data: { guess: guess, email: currEmail }
});
lastModal.className = 'modal';
main.className = 'hide';
}
}
};
guess = '';
});
for (var i = numbers.length - 1; i >= 0; i--) {
numbers[i].addEventListener('click', function(){
reset = 0;
nextSpan(this.innerHTML);
});
};
function nextSpan (currNumber){
for (var i = 0; i < screenSpans.length; i++) {
if (screenSpans[i].innerHTML == '' && reset == 0){
screenSpans[i].innerHTML = currNumber;
reset = 1;
}
};
}
/*
|---------------------------------------------------
| FORM SUBMIT CHECK
|---------------------------------------------------
*/
var submitButton = document.getElementById('startButton');
var form = document.getElementById('form');
var goAhead = true;
submitButton.addEventListener('click', function(){
var i, j, q = [];
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].nodeName == "INPUT"){
q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
var inputValue = encodeURIComponent(form.elements[i].value)
if ((inputValue == '' || inputValue == null) && (form.elements[i].name != 'online')){
// NOT COMPLETE
goAhead = false;
console.log(form.elements[i].name)
}
}
}
if (goAhead){
// SUBMIT
document.getElementById('form').submit();
} else {
this.innerHTML = "Please fill out all the fields & try again";
setTimeout(function(){
submitButton.innerHTML = "Let's Play!";
}, 7000);
goAhead = true;
}
});
$('#createFields').click(function () {
for (var i = 0; i <= numberOfFields; i++) {
fieldsArray[i] = {};
console.log(fieldsArray);
};
});
i get the numberOfFields variable from a select box
$("body").on("change","input:checkbox",
function () {
if ($(this).prop('checked')) {
var val = $(this).prop('value');
addColumns(val);
}
else {
console.log("deleting...")
singleArray=singleArray.splice(singleArray.length, newArray.length);
InitData();
}
}
);
I call the addColumns function each time a checkbox is checked.
function addColumns(val) {
var defer = $.Deferred();
newArray = [];
str = [];
str.push(val);
var url = ListJoin.appweburl + "/_api/SP.AppContextSite(#target)/Web/Lists/getbytitle('" + selectedList + "')/items?$select=" + str + "" +
"&#target='" + ListJoin.hostweburl + "'";
ListJoin.executor.executeAsync({
url: url,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (data) {
var jsonObject = JSON.parse(data.body);
var response = jsonObject.d.results;
for (var i = 0, len = response.length; i < len; i++) {
var tu = [];
var keys = Object.keys(response[i]);
//Skip keys[0] because it's always metadata
for (var j = 1; j < keys.length; j++) {
var key = keys[j];
var val = [response[i][key]];
console.log("bujar" + val);
newArray.push(val);
}
}
fieldsArray[1].push(newArray);
can not push neither concat newArray=['BBB','MMM','CCC'] to the an array of the fieldsArray array
InitData();
defer.resolve();
},
error: function (data) {
console.log(data);
defer.reject();
}
});
return defer;
}
am having script with working condition but many for loop is there so any way to do this...to simplify this ...am new to script kindly help on this....
function change()
{
//document.getElementById("Geography").options[7]=new Option("", "newval", true, false);
var geo = document.getElementById("Geography").options;
var zon = document.getElementById("zone").options;
var coun = document.getElementById("country").options;
for (var i = 0; i < geo.length; i++)
{
if (geo[i].innerHTML == "Null Value" || geo[i].innerHTML == "")
{
document.getElementById("Geography").options[i] = null;
}
}
for (var i = 0; i < coun.length; i++)
{
alert("Loop1" + i);
if (coun[i].innerHTML == "Null Value")
{
document.getElementById("country").options[i] = null;
}
}
for (var i = 0; i < zon.length; i++)
{
//alert("Loop1" + i);
if (zon[i].innerHTML == "Null Value")
{
document.getElementById("zone").options[i] = null;
}
}
}
To remove an option, call removeChild() on the parent element.
var geoSel = document.getElementById("Geography");
var geo = geoSel.options;
for (var i = geoSel.options.length-1; i >= 0; i--) {
if (geo[i].innerHTML == "Null Value" || geo[i].innerHTML == "") {
geo.removeChild(geo[i]);
}
}
I count down instead of up because removing a child will cause the indexes of all the following children to be shifted down. In a count-up loop, that will cause elements to be skipped.
use this UPDATED DEMO
function change(){
var optionsArr = [];
optionsArr.push(document.getElementById("Geography").options);
optionsArr.push(document.getElementById("zone").options);
optionsArr.push(document.getElementById("country").options);
var optArrlenght = optionsArr.length;
for ( var j = 0; j < optArrlenght; j++){
var options = optionsArr[j];
var optionslength = options.length;
for (var i = 0; i < optionslength; i++)
{
if (options[i].innerHTML == "Null Value" || options[i].innerHTML == "")
{
options[i].remove();
i--;
optionslength--;
}
}
}
}
change();
I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}