async functions inside jquery each() loops - javascript

I have a loop running for each selected checkbox in Javascript / Jquery.
Inside this loop I call an async function that will return a Tile Layer(Image).
I have to pass to this function a parameter called checkboxPermanent.
After this function is called the variable checkboxPermanent changes its value, not sure why.
In the sequence it calls a similiar function but now passing the same variable but with the wrong parameter value.
$('#exec-perm').on('click', function () {
var checkboxPermanent;
$('#checks-perm input').each(async function () {
checkboxPermanent = $(this).attr('value');
isChecked = $(this).prop('checked');
permanent = permanent_layers[checkboxPermanent] // começa com valor undefined, no próximo loop passa a conter um objeto para que possa cair na codição 1
pixel_permanent = pixel_permanent_layers[checkboxPermanent]
if (permanent) {
if (!isChecked) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
} else if (isChecked && state_faz == faz_value && state_ano_safra == ano_safra_value && state_profundidade == profundidade_value) {
//map.addLayer(permanent)
//map.addLayer(pixel_permanent)
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
} else if (isChecked && (state_faz != faz_value || state_ano_safra != ano_safra_value || state_profundidade != profundidade_value)) {
map.removeLayer(permanent)
map.removeLayer(pixel_permanent)
ctrlLayers.removeLayer(permanent)
ctrlLayers.removeLayer(pixel_permanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
} else if (isChecked) {
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
pixel_permanent = wmsPixelPermCall(checkboxPermanent, faz_value, profundidade_value);
//console.log(checkboxPermanent)
permanent_layers[checkboxPermanent] = permanent; // armazena o valor no array para que possa cair na condicional que irá excluir os layers do control
pixel_permanent_layers[checkboxPermanent] = pixel_permanent;
//map.addLayer(permanent);
//map.addLayer(pixel_permanent);
ctrlLayers.addOverlay(permanent, 'Mapa de ' + checkboxPermanent);
ctrlLayers.addOverlay(pixel_permanent, 'Mapa de ' + checkboxPermanent + ' - Pixels');
}
if (checkboxPermanent == 'altimetria') {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
} else {
leg_permanent[checkboxPermanent] = 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value
leg_pixel_permanent[checkboxPermanent] = 'Emp:mv_' + checkboxPermanent + '_sql'
}
});
})
If I console.log(checkboxPermanent) before wmswmsPermRasterCall(). It will return the right value. If I console.log(checkboxPermanent) right after wmswmsPermRasterCall() is called it gets a different value..
async function wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value) {
//var colorRampSLD = getStyles(faz_value, checkboxPermanent)
if (checkboxPermanent == 'altimetria') {
var raster_name = checkboxPermanent + '_' + faz_value
getColors = await getStyles(faz_value, checkboxPermanent)
var colorEnv = '';
for (var j = 0; j < getColors.length; j++) {
if (j + 1 >= getColors.length) {
colorEnv += 'c' + j + ':' + getColors[j]
} else {
colorEnv += 'c' + j + ':' + getColors[j] + ';'
}
}
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + raster_name,
transparent: true,
format: 'image/png',
}).setParams({
env: colorEnv
})
} else {
return L.tileLayer.wms('http://localhost:8080/geoserver/Emp/wms', {
layers: 'Emp:' + checkboxPermanent + '_' + faz_value + '_p' + profundidade_value,
transparent: true,
format: 'image/png',
})
}
}
What Am I missing here?

Check here:
console.log(checkboxPermanent)
permanent = wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
This function is async, it will run outside of your function, your code will continue before wmsPermRasterCall is finished.
You need to wait for the result of wmsPermRasterCall using await:
console.log(checkboxPermanent)
permanent = await wmsPermRasterCall(checkboxPermanent, faz_value, profundidade_value);
console.log(permanent)
Your code will halt until wmsPermRasterCall is finished.

Related

Dynamic API CALL/ Retrieving specific Attributes

I am doing an API call and data fetching with Fetch function on a platform listing different products with their data identified by attributes, here I am trying to fetch multiple attributes of a specific category of product, each product is identified by a unique serial number, which serves as my entry key to retrieve product data.
Or the attributes that I retrieve do not exist for certain products, either the field exists but the data is null, or the field is not filled in on the platform for this product.
I neutralize nulls with the formula you can see on my script but it doesn't always work, I would like to know if I can make my API even more dynamic, i.e. retrieve attributes only when they exist and when the presence of a null does not block the API call.
function GetAllProduct() {
var token=ConnectAlkemics();
//Logger.log(token);
var headers ={
"accept": "*/*",
"accept-language": "fr",
'Authorization' : 'Bearer ' + token,
'cache-control': 'no-cache',
'content-type': 'application/json;charset=UTF-8',
'expires': '-1',
'pragma': 'no-cache',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-site',
'x-alk-priority': '9'
};
var options ={
'method' : "GET",
"headers" : headers
};
var source =SpreadsheetApp.getActive().getSheetByName("GTIN");
var ss =SpreadsheetApp.getActive().getSheetByName("RESULTATS");
ss.clear();
// var dico=CreerDicoHeader();
//retrieving list of attribute
var lastRow = source.getLastRow();
var listeAttribut = "";
var listeChamp = "";
var tabChamp = [];
var index = 0;
for(var i = 2; i <= lastRow; i++ ){
//Logger.log(i);
if(source.getRange(i, 3).getValue() != ""){
tabChamp[index] = source.getRange(i, 2).getValue();
index +=1;
if(listeAttribut == ""){
listeAttribut = source.getRange(i, 3).getValue();
listeChamp = source.getRange(i, 2).getValue();
}
else{
listeAttribut = listeAttribut + "," + source.getRange(i, 3).getValue();
listeChamp = listeChamp + "," + source.getRange(i, 2).getValue();}
}
}
var total=0;
var debut=2;
var moregtin=true
var lignegtin=1;
var colonnes=[
"GTIN",
"Libelle long",
"Fournisseur",
"Catégorie du produit",
"Code Tiers",
"Cycle de vie",
"Maturité commande Galec",
"Maturité direct magasin" ,
"Maturité Commande SCABEL",
"Maturité complémentaire Galec",
"Maturité complémentaire Direct Magasin",
"Maturité complémentaire Scabel",
"Maturité Animation Digitale",
"Maturité Digitale",
"Maturité Entité Leclerc",
"Type d'unité",
"Marque Commerciale",
"Appellation viticole ou région d'origine",
"Complément d'appellation(N)",
"Packaging vin",
"Contenu net",
"Description des saveurs du vin",
"Type de champagne(N)",
"Viticulture(N)",
"Couleur du Vin",
"Millésime",
"Terroirs et sol(N)",
"Région Viticole",
"Durée du potentiel de maturation",
"Echelle de fruit",
"Echelle de personnalité",
"Dégustation robe",
"Dégustation nez",
"Type de vendange(N)",
"Dégustation bouche",
"Type d'appellation du vin",
"Allergènes avérés",
"Type d'allergène",
"Degré d'alcool",
"Teneur en sucre",
"Description du cépage",
"Accords mets et vins",
"Occasions particulières",
"Températures de dégustation (en °c)",
"Potentiel de garde",
"Code de nomenclature douanière",
"Code produit accise france",
"Libellé fiscal",
"Pays d'origine",
"Type de paiement des droits d'alcools",
"Image Face du produit",
"Image Arrière du produit",
];
var colonnematurite=6; //Colonnes
for(i=0;i<colonnes.length;i++) {
ss.getRange(1,i+1).setValue(colonnes[i]);
}
//for(i=0; i<tabChamp.length; i++){
// ss.getRange(1,i+1).setValue(tabChamp[i]);
//Logger.log(tabChamp[i]);
//}
while (moregtin==true)
{
var fini=false;
var nbgtin=0;
var lesgtin="";
var produits =[];
while ((source.getRange(lignegtin,1).getValue()!="") && (nbgtin<50)) //paquets de 50 GTINs
{
if (lesgtin!="")
lesgtin=lesgtin+",";
lesgtin=lesgtin+source.getRange(lignegtin,1).getValue().toString().replace(/\s+/g," ").trim();
lignegtin=lignegtin+1;
nbgtin=nbgtin+1;
}
if (lesgtin=="")
{
moregtin=false;
fini=true;
}
else
{
var limit=200;
var next_page='';
var lastparam='';
var params =lastparam + 'status_shared_from=4' + lesgtin + '&filter_source_include=uuid,gtin,namePublicLong,namePublicShort,isSharedFrom.sourceOrganization.nameLegal,endAvailabilityDateTime,supplierId,business_processes,brand.description,lastOrderDateTime,isUserLabeledByName,lifeCycle,typePackaging,isConsumerUnit,isBaseUnit,isDisplayUnit,assets,pictures,exportables'
var params =lastparam + '&filter_product_languages=fr&filter_gtins_in=' + lesgtin + '&filter_source_include=' + listeAttribut
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
}
while (fini==false) {
var lesparams =params + '&limit=' + limit + '&next_page=' + next_page + '&ts=' + Math.floor((Math.random() * 10000000) + 1);
var url='https://apis.alkemics.com/public/v1/products?'+lesparams;
//Logger.log(url);
var content =UrlFetchApp.fetch(url, options);
//Logger.log(content);
//Logger.log(content.getResponseCode())
if (content.getResponseCode() ==200) {
var retour =JSON.parse(content.getContentText());
next_page=retour.next_page;
var data=retour.data;
for(i=0; i<data.length;i++) {
var produit=data[i]; // Un produit au format JSON
var libellelong="";
try
{
libellelong=produit.namePublicLong[0].data;
}
catch(e) {
libellelong="";
//libelle="NA"
}
var libellecourt="";
try
{
libellecourt=produit.namePublicShort[0].data;
}
catch(e) {
libellecourt="";
//libelle="NA"
}
var maturite={}
for(k=0;k<produit.business_processes.length;k++)
{
maturite[produit.business_processes[k].label]=(produit.business_processes[k].requested==false?"":(produit.business_processes[k].status==true?"OK":"KO"));
}
var listematurite={}
for(k=0;k<produit.business_processes.length;k++)
{
listematurite[k]=produit.business_processes[k].label;
}
var marque=""
if ("brand" in produit) {
if ("description" in produit.brand)
marque=produit.brand.description;
}
var occasionwhine=""
if (" occasions" in produit) {
if("occasion" in produit.occasions[0])
occasionwhine = produit.occasions[0].occasion.label
}
var pairing=""
if (" pairingsTypes" in produit) {
if("pairingsType" in produit.pairingsTypes[0])
pairing = produit.pairingsTypes[0].pairingsType.label
}
var mediaface= ""
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[0])
mediaface= produit.assets.pictures[0].exportables[0].uniformResourceIdentifier
}
var mediaback
if (" assets" in produit) {
if("pictures" in produit.assets)
if("exportables" in produit.assets.pictures[2])
mediaback= produit.assets.pictures[2].exportables[0].uniformResourceIdentifier
}
//var ConsumerUnit = (produit.isConsumerUnit == false ?"":(produit.isBaseUnit==true?"UC":"LOT"))
//var Presentoir = (produit.isDisplayUnit == true ? produit.typePackaging.label : "")
var ligne=[
produit.gtin,
libellelong,
produit.isSharedFrom[0].sourceOrganization.nameLegal,
produit.kind != null? produit.kind.label: ' ',
produit.supplierId,
produit.lifeCycle,
//(produit.endAvailabilityDateTime==null?"":TIMESTAMP_TO_DATE(produit.endAvailabilityDateTime)),
//produit.isUserLabeledByName,
maturite[tabChamp[colonnematurite]],
maturite[tabChamp[colonnematurite+1]],
maturite[tabChamp[colonnematurite+2]],
maturite[tabChamp[colonnematurite+3]],
maturite[tabChamp[colonnematurite+4]],
maturite[tabChamp[colonnematurite+5]],
maturite[tabChamp[colonnematurite+6]],
maturite[tabChamp[colonnematurite+7]],
maturite[tabChamp[colonnematurite+8]],
produit.typePackaging.label,
marque,
produit['alcoholicBeverageSubregionText'],
produit['alcoholicBeverageAdditionalAppellationDetailsText'],
produit.leclercWinePackagingTypeCode != null? produit.leclercWinePackagingTypeCode.label : ' ',
produit.netWeight[0] != null? produit.netWeight[0].data: ' ',
produit.wineTastingDescriptionList[0] != null?
produit.wineTastingDescriptionList[0].wineTastingCode.label : ' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.vintnerTextList,
produit.colorGroup != null? produit.colorGroup.label: ' ',
produit.vintage,
produit.vineyardRegion != null? produit.vineyardRegion.label: ' ',
produit.leclercFrenchVineyardRegionCode != null? produit.leclercFrenchVineyardRegionCode.label: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label: ' ',
produit.wineFruitExpressionNoteNumber,
produit.wineAromasExpressionNoteNumber,
produit.wineTastingRobeDescriptionText[0] != null? produit.wineTastingRobeDescriptionText[0].data: ' ',
produit.wineTastingNoseDescriptionText[0] != null? produit.wineTastingNoseDescriptionText[0].data: ' ',
produit['grapeHarvestingDescriptionText'].data,
produit.wineTastingMouthDescriptionText[0] != null? produit.wineTastingMouthDescriptionText[0].data:' ',
produit.wineCategoryCode != null? produit.wineCategoryCode.label: ' ',
produit.allergens[0] != null? produit.allergens[0].data : ' ',
produit.allergenTypeList,
produit.ratioAlcohol,
produit.sugarContent != null? produit.sugarContent.label: ' ',
produit.varietalDesignationDescriptionText[0] != null? produit.varietalDesignationDescriptionText[0].data:' ',
pairing,
//produit.pairingsTypes[0] != null? produit.pairingsTypes[0].pairingsType.label: ' ',
occasionwhine,
//produit.occasions[0].occasion != null? produit.occasions[0].occasion.label: ' ' , //+ "," + produit.occasions[1],
produit.tempConsumption[0] != null? produit.tempConsumption[0].data: ' ',
produit.wineAgeingPotentialDurationCode != null? produit.wineAgeingPotentialDurationCode.label : ' ',
produit.importEuropeanClassification,
produit.cpaFranceCode.label,
produit.taxLabelList[0] != null? produit.taxLabelList[0].taxLabelCode.label: ' ',
produit.countryOfOriginList[0] != null? produit.countryOfOriginList[0].countryOfOriginCode.label: ' ',
produit.alcoholicBeveragePaymentTypeCode != null? produit.alcoholicBeveragePaymentTypeCode.label: ' ',
mediaface,
mediaback,
//produit.assets.pictures[0].exportables[0] != null? produit.assets.pictures[0].exportables[0].uniformResourceIdentifier: ' ',
// produit.assets.pictures[2].exportables[0] != null? produit.assets.pictures[2].exportables[0].uniformResourceIdentifier: ' ',
//ConsumerUnit,
//Presentoir
];
produits.push(ligne);
total=total+1;
}
}
else {
Logger.log('Error in GET /contents/{contentid}')
}

How to decode Javascript _0x Hex

I tried to decode this code but I did not succeed:
var _0x147bb5 = _0xe0c4, _0x41852d = _0xe0c4, _0x39ac2c = _0xe0c4;
(function (_0x3c89e2, _0x4b3ebe) {
var _0x331330 = _0xe0c4, _0x279707 = _0xe0c4, _0x50917c = _0xe0c4, _0x489044 = _0x3c89e2();
while (!![]) {
try {
var _0x36e386 = -parseInt(_0x331330(0x133)) / 0x1 + -parseInt(_0x279707('0x12a')) / 0x2 + -parseInt(_0x331330(0x111)) / 0x3 + -parseInt(_0x331330(0x12f)) / 0x4 + parseInt(_0x279707('0x10a')) / 0x5 * (-parseInt(_0x279707('0xf1')) / 0x6) + -parseInt(_0x331330('0x109')) / 0x7 + parseInt(_0x331330(0xee)) / 0x8 * (parseInt(_0x279707(0x11a)) / 0x9);
if (_0x36e386 === _0x4b3ebe) break; else _0x489044['push'](_0x489044['shift']());
} catch (_0x108487) {
_0x489044['push'](_0x489044['shift']());
}
}
}(_0x5a9e, 0x7f5a2));
var s = _0x147bb5('0x12b') + _0x147bb5(0xdc) + _0x39ac2c('0x118') + '91', f = 0xb, l = lf(), message = _0x39ac2c('0x117') + _0x39ac2c('0xe7') + _0x39ac2c('0x108') + _0x147bb5('0xd4') + 'ot\x20' + _0x147bb5('0x104') + _0x41852d(0xd3) + _0x39ac2c('0x122') + _0x39ac2c('0xef') + _0x41852d(0x127) + _0x41852d('0x102') + _0x41852d('0xfb') + _0x147bb5(0xe2) + _0x39ac2c(0xf2) + _0x147bb5(0xe5) + _0x41852d(0xd6) + _0x39ac2c(0x125) + _0x41852d(0xff) + _0x147bb5(0xd7) + _0x41852d('0x110') + _0x39ac2c('0x11e') + _0x39ac2c(0xdd) + _0x41852d(0x107) + 'ea)';
function rtclickcheck(_0xf37bcd) {
var _0x5b07b6 = _0x39ac2c, _0x189d42 = _0x41852d, _0x158d5e = _0x147bb5;
if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf5) + 'e'] == _0x158d5e('0xe4') + _0x189d42(0xde) + 'pe' && _0xf37bcd[_0x5b07b6('0xfc') + 'ch'] == 0x3) return alert(message), ![];
if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf8) + _0x5b07b6('0x11d') + 'n'][_0x5b07b6('0xec') + _0x158d5e(0x128) + 'f'](_0x158d5e(0xe6) + 'E') != -0x1 && event[_0x189d42('0x126') + _0x158d5e('0x132')] == 0x2) return alert(message), ![];
} function _0x5a9e() {
var _0x521b96 = ['Thi', '7109872DszjuD', '4405xemFJj', 'deA', '//r', 'cre', 'hre', 'h=/', 're.', '1823784ZeLCWd', ';\x20p', 'etc', 'cap', 'cha', 'crt', 'Ooh', '794', 'TCS', '14494869UZdEDp', 'onm', 'erH', 'sio', 'com', 'ute', 'dli', 'men', 'py\x20', '_y=', 'tBy', 'uth', 'but', 'rot', 'exO', 'inn', '603236FmaGTN', '-11', 'exp', 'ous', 'toU', '2882436fEtPRL', 'dit', 'kie', 'ton', '1000745kgQiEE', '\x20Co', 's\x20N', 'hos', '//y', 'sto', 'len', 'pat', 'tri', '.ly', '350', '\x20(y', 'sca', 'gth', 'lin', 'rib', 'by\x20', 'Att', 'Net', 'ps:', 'MSI', '!!\x20', 'edo', 'ide', 'tna', '10;', 'ind', '/yu', '24DoydZk', '-\x20P', 'rCo', '4518TXMdnf', 'htt', 'N_f', 'Ele', 'Nam', 'and', 'get', 'Ver', 'ire', 'ati', 'ed\x20', 'whi', 'app', 'coo', 'eme', 'TML', 'ath', 'ect', 'sli', 'For', 'Tim', 'set', 'uid'];
_0x5a9e = function () {
return _0x521b96;
};
return _0x5a9e();
}
document[_0x147bb5(0x11b) + _0x147bb5('0x12d') + _0x147bb5('0xe8') + 'wn'] = rtclickcheck;
if (l == s && s[_0x147bb5(0xd8) + _0x147bb5('0xdf')] == f) {
var ceditf = document[_0x147bb5(0xf7) + _0x41852d(0xf4) + _0x39ac2c('0x121') + _0x147bb5(0x124) + 'Id'](_0x39ac2c(0x10d) + _0x147bb5('0x130') + _0x147bb5('0xe0') + 'k'), citf = document[_0x39ac2c(0xf7) + _0x147bb5('0xf4') + _0x39ac2c('0x121') + _0x39ac2c('0x124') + 'Id'](_0x39ac2c('0x116') + _0x39ac2c(0xe0) + 'k');
o();
var citdf = document[_0x41852d('0xf7') + _0x147bb5('0xf4') + _0x41852d(0x121) + _0x41852d('0x124') + 'Id'](_0x41852d('0x116') + _0x147bb5('0x120') + 'nk');
function checkLIC() {
var _0x4072d7 = _0x41852d, _0x264ab4 = _0x41852d, _0x1a0d97 = _0x147bb5;
if (cedit['inn' + _0x4072d7('0x11c') + _0x4072d7(0x100)][_0x1a0d97('0xd8') + _0x4072d7('0xdf')] === 0x0) return invalidLIC(), ![];
}
}
var cedit = document[_0x41852d(0xf7) + _0x39ac2c(0xf4) + _0x39ac2c(0x121) + _0x41852d('0x124') + 'Id'](_0x147bb5('0x10d') + _0x39ac2c(0x130) + _0x39ac2c(0xe0) + 'k');
function _0xe0c4(_0x488be0, _0x324154) {
var _0x5a9e88 = _0x5a9e();
return _0xe0c4 = function (_0xe0c4a8, _0x3812b4) {
_0xe0c4a8 = _0xe0c4a8 - 0xd3; var _0x1108f7 = _0x5a9e88[_0xe0c4a8];
return _0x1108f7;
}, _0xe0c4(_0x488be0, _0x324154);
}
!cedit && invalidLIC();
function o() {
_0x162858();
function _0x162858() {
var _0x139ac8 = _0xe0c4, _0x75417f = _0xe0c4, _0x15d340 = _0xe0c4, _0x5960f5 = new Date();
_0x5960f5[_0x139ac8(0x106) + _0x75417f('0x105') + 'e'](_0x5960f5[_0x75417f(0xf7) + _0x15d340(0x105) + 'e']() + 0x15180 * 0x3);
var _0x43eec0 = _0x75417f(0x12c) + _0x15d340(0xf9) + 's=' + _0x5960f5[_0x15d340('0x12e') + _0x139ac8(0x119) + _0x139ac8(0xda) + 'ng']();
document[_0x15d340('0xfe') + 'kie'] = _0x15d340(0x114) + _0x139ac8('0x123') + _0x15d340('0xeb') + _0x15d340('0xd9') + _0x75417f('0x10f') + ';', document[_0x75417f(0xfe) + _0x15d340('0x131')] = 'JSO' + _0x139ac8(0xf3) + _0x75417f('0x113') + 'h' + '=' + fetchon + ';' + _0x43eec0 + (_0x139ac8(0x112) + _0x15d340('0x101') + '=/'), window['loc' + _0x15d340(0xfa) + 'on'][_0x15d340('0x10e') + 'f'] = api;
}
}
function invalidLIC() { }
function checkLIC() {
var _0x4dac69 = _0x39ac2c, _0x55bc12 = _0x41852d, _0x4c895a = _0x147bb5;
if (cedit[_0x4dac69(0x129) + _0x4dac69('0x11c') + _0x4c895a(0x100)][_0x55bc12('0xd8') + _0x4dac69(0xdf)] === 0x0) return invalidLIC(), ![]; else {
if (cedit[_0x4c895a('0xf7') + _0x55bc12(0xe3) + _0x55bc12(0xe1) + _0x4c895a('0x11f')](_0x4dac69(0x10e) + 'f') !== _0x4c895a(0xf2) + _0x4c895a('0xe5') + _0x55bc12('0x10c') + 'ebr' + _0x4c895a('0xf6') + _0x4c895a(0xdb) + _0x55bc12('0xed') + _0x4c895a(0xe9) + 'a/') return invalidLIC(), ![];
}
}
checkLIC(),
setInterval(
function () {
checkLIC();
},
0x1388
);
function lf() {
var _0x5a8bac = _0x39ac2c, _0x505e9a = _0x147bb5, _0xd36b1d = _0x147bb5, _0x5b07b5 = location[_0x5a8bac(0xd5) + _0x505e9a('0xea') + 'me'][_0x5a8bac(0x103) + 'ce'](0x2)[_0x505e9a(0x103) + 'ce'](0x0, -0x2) + '24', _0x130606 = 0x0;
if (_0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d('0xdf')] == 0x0) return _0x130606;
for (i = 0x0; i < _0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d(0xdf)]; i++) {
char = _0x5b07b5[_0xd36b1d('0x115') + _0xd36b1d('0xf0') + _0xd36b1d(0x10b) + 't'](i), _0x130606 = (_0x130606 << 0x5) - _0x130606 + char, _0x130606 = _0x130606 & _0x130606;
}
return _0x130606;
}
https://jsfiddle.net/utpgLw06/
So My first approach is to use online tools, but none of them works. I also try to manually decode it by calling the function name console.log(_0x331330(0x133)) but it just shows strings that I don't understand. I also tried to decode those strings by using much hex at numerical decoders but none of them works. Anyone can help me, please?
I played a bit with this code:
The _Ox names are just variable names. You can make the code more readable by collecting all such distinct names and replace them with more readable names, like v1, v2, v3, ....
There are two variables referenced which are not defined, api and fetchon. I suppose that the page where this script runs, has defined them somewhere.
The first part of the script is harmless and just shuffles an array of strings, which is later used to obfuscate strings (often property names). You can execute it
The code that needs de-obfuscation is the code that gets/sets properties of window, document, nagivator, ...and other objects. You can get a long way by putting that part of the script in a template literal, and evaluating all those expressions that evaluate to a property name, or to a value assigned to a property.
Functions and immediate code are mixed. It helps to reorganise that a bit.
Some functions have local variables which are constants and have unique names. These can be moved to the global scope and can often be evaluated safely, so the rest of the function's code can be clarified inside a template literal (like explained above).
Any remaining variables (not evaluated), can be given more telling names by seeing how they are used.
Anyway, here is the result I got to:
function rtclickcheck(e) {
if (navigator.appName == "Netscape" && e.which == 3)
return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false;
if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2)
return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false;
}
document.onmousedown = rtclickcheck;
function o() {
var date = new Date();
date.setTime(date.getTime() + 259200);
var expiration = "expires=" + date.toUTCString();
document.cookie = "cap_y=10;path=/;";
// fetchon and api must be defined?
document.cookie = "JSON_fetch=" + fetchon + ";" + expiration + "; path=/";
window.location.href = api;
}
function invalidLIC() { }
function checkLIC() {
if (cedit.innerHTML.length === 0)
return invalidLIC(), false;
else {
if (cedit.getAttribute("href") !== "https://rebrand.ly/yuidea/")
return invalidLIC(), false;
}
}
function lf() {
var decrypted = location.hostname.slice(2).slice(0, -2) + '24',
encrypted = 0;
if (decrypted.length == 0) return encrypted;
for (i = 0; i < decrypted.length; i++) {
char = decrypted.charCodeAt(i);
encrypted = (encrypted << 5) - encrypted + char;
encrypted = encrypted & encrypted;
}
return encrypted;
}
var l = lf();
var s = "-1135079491";
if (l == s && s.length == 11) {
var ceditf = document.getElementById("creditlink"),
citf = document.getElementById("crtlink");
o();
var citdf = document.getElementById("crtdlink");
function checkLIC() {
if (cedit.innerHTML.length === 0)
return invalidLIC(), false;
}
}
var cedit = document.getElementById("creditlink");
!cedit && invalidLIC();
checkLIC();
setInterval(checkLIC, 5000);
This code seems to do the following things:
Avoid that the user can view the source of the page with a right click
Obfuscates the current site's hostname through bitshifting and summing, and checks that the result has a certain value. I didn't try to find out what the original hostname would have to be to get a match.
Sets some variables like ceditf which are not used in this script, but maybe elsewhere
If the host matches, two cookies are set, and a navigation occurs (to whatever api has as URL)
Every 5 seconds checks the content of the element with id "creditlink".
If the contents of "creditlink" are not as expected it calls invalidLIC, but that function is empty -- I think that might have had code in a previous version of this script, but it was later removed.

Order in jQuery calls

I have a jQuery loop that iterates over specifics elements of an HTML page. For every element, I do a switch over a variable and append HTML code in specific places.
The problem is that, one of those appends is an import to another Javascript file. This file uses a variable from the first one but, for some reason, that variable doesn't always have the correct value, depending on the order of the HTML elements in the page.
UPDATE
As requested, I created a Plunker so it's easy to see code:
http://plnkr.co/edit/mrEhgbZhhvu0Z4iniXGl?p=preview
Note: For this to work, you need to have correct pageId and appId for Instagram.
I'll put the code to be more clear:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="estilo.css">
</head>
<body>
<section id="rrss">
<!-- If I put this article block as the last one, it works -->
<article id="instagram">
<div data-rrss="instagram"></div>
</article>
<br/>
<article id="facebook">
<div data-rrss="facebook"></div>
</article>
<br/>
<article id="twitter">
<div data-rrss="twitter"></div>
</article>
</section>
<!-- SCRIPTS -->
<script src='scripts/data.js'></script>
<script src='scripts/jquery.js'></script>
<script>var customJquery = $.noConflict(true);</script>
<script src='../magic.js'></script>
</body>
</html>
data.js
var data = {
"facebook": {
"id": "facebook",
"width": 0,
"height": 0,
"custom_style": "border:none;overflow:hidden",
"hide_cover": false,
"show_facepile": true,
"small_header": false,
"adapt_container_width": true
},
"twitter": {
"id": "twitter",
"width": 0,
"height": 0,
"chrome": "nofooter noscrollbar noheader", // noborders transparent
"tweet_limit": 0,
"lang": "es",
"theme": "dark",
"link_color": "#0084b4"
},
"instagram": {
"id": "123456798123467/9876543219876543",
"hidecaption": false,
"custom_style": "overflow:auto;",
"max_width": 0,
"max_height": 500
},
"defaults": {
"width": 380,
"height": 500
}
}
magic.js
var rrss = customJquery('div[data-rrss]');
var conf = undefined;
var defaults = undefined;
var node = document.querySelectorAll('[data-rrss="instagram"]')[0];
customJquery.each(rrss, function(ix, it) {
var html = '';
var network = customJquery(it).data('rrss');
if (network === undefined || network == null || network.length <= 0)
return;
conf = data[network];
if (conf === undefined ||conf === null || conf.length <= 0)
return;
defaults = data['defaults'];
//Comprobamos si existe el key y si el value tiene texto
if(conf.id === undefined || conf.id === null || conf.id.length === 0)
return;
switch(network) {
case 'facebook':
html = '<iframe id="iFB" src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2F' + conf.id +
'&tabs=timeline' +
'&width=' + (conf.width <= 0 ? defaults.width : conf.width) +
'&height=' + (conf.height <= 0 ? defaults.height : conf.height) +
'&small_header=' + conf.small_header +
'&adapt_container_width=' + conf.adapt_container_width +
'&hide_cover=' + conf.hide_cover +
'&show_facepile=' + conf.show_facepile + '"' +
'width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ' +
'style="' + conf.custom_style + '" ' +
'scrolling="no" frameborder="0" allowTransparency="true" allow="encrypted-media"></iframe>\n' +
'<script type="text/javascript">\n' +
' setInterval(() => {\n' +
' customJquery("#iFB")[0].src = customJquery("#iFB")[0].src\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
case 'twitter':
html = '<a class="twitter-timeline" '+
'href="https://twitter.com/' + conf.id + '" ' +
'data-width="' + (conf.width <= 0 ? defaults.width : conf.width) + '" ' +
'data-height="' + (conf.height <= 0 ? defaults.height : conf.height) + '" ';
if (conf.chrome !== undefined && conf.chrome !== '') {
html += 'data-chrome="' + conf.chrome + '" ';
}
if (conf.tweet_limit > 0) {
html += 'data-tweet-limit="' + conf.tweet_limit + '" ';
}
html += 'data-lang="' + conf.lang + '" ' +
'data-theme="' + conf.theme + '" ' +
'data-link-color="' + conf.link_color + '"' +
'>Tweets by ' + conf.id + '</a>\n' +
'<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>';
break;
case 'instagram':
node = node.parentElement;
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../insta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
default:
html = '';
}
if (html != '') {
customJquery(it).replaceWith(html);
}
});
insta.js
window.fbAsyncInit = function () {
var html = '';
var style = '';
// When the Instagram's article bloke in HTML isn't the last one, this shows data from Twitter bloke
console.log(conf);
if (node !== undefined) {
if (document.getElementById('instagram') !== null) {
document.getElementById('instagram').innerHTML = '';
}
if (conf !== undefined && conf !== '') {
if (conf.max_width !== undefined && conf.max_width > 0) {
style += 'max-width: ' + conf.max_width + 'px;';
} else {
style += 'max-width: ' + defaults.width + 'px;';
}
if (conf.max_height !== undefined && conf.max_height > 0) {
style += 'max-height: ' + conf.max_height + 'px;';
} else {
style += 'max-height: ' + defaults.height + 'px;';
}
style += conf.custom_style;
}
var div = document.createElement('div');
div.id = 'instagram';
if (style !== '') {
div.style = style;
}
node.appendChild(div);
}
var pageId = conf.id.substring(0, conf.id.indexOf('/'));
var appId = conf.id.substring(conf.id.indexOf('/') + 1);
FB.init({
appId: appId,
autoLogAppEvents: true,
xfbml: true,
version: "v3.1"
});
FB.getLoginStatus(function (response) {
if (response.status === "connected") {
FB.api(
"/" + pageId + "/",
"GET", { "fields": "instagram_business_account" },
function (response) {
if (response.error && response.error !== '') {
console.log("Error recovering 'instagram_business_account': " + response.error.message);
} else {
FB.api(
"/" + response.instagram_business_account.id + "/media",
"GET", { "fields": "shortcode" },
function (response) {
for (var i = 0; i < response.data.length; i++) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
html = JSON.parse(this.response).html;
document.getElementById("instagram").innerHTML += html;
}
};
xhttp.open("GET", "https://api.instagram.com/oembed/?url=http://instagr.am/p/" + response.data[i].shortcode + "&omitscript=true&hidecaption=" + conf.hidecaption, true);
xhttp.send();
}
}
);
}
}
);
} else {
console.log("Error recovering access token: Not connected.")
console.log(response)
}
});
};
Well, I've solved with some ugly lonely line:
case 'instagram':
node = node.parentElement;
instaconf = conf; // ***** Saved the conf here *****
html = '<script async src="https://connect.facebook.net/es_ES/sdk.js"></script>\n' +
'<script src="../tecInsta.js"></script>\n' +
'<script async defer src="https://www.instagram.com/embed.js"></script>\n' +
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' fbAsyncInit();\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
break;
Then changed the conf references to instaconf in insta.js file.
Since this file was loaded after the jQuery loops ended, the configuration was the last one in that loop (the last article in index.html file).
Here the problem is you are appending HTML elements dynamically. Here jquery will append in DOM then browser will some time to parse. Until that controller wont wait for the operation so loop continue execution. so here config is hold last element of twitter configuration.
And we can't pass reference to html string as per my knowledge. This we can achieve by passing config as string into html string from there we can pass to fbAsyncInit() method.
'<script>\n'+
' setInterval(() => {\n' +
' if (document.readyState === "complete") {\n' +
' window.instgrm.Embeds.process();\n' +
' }\n' +
' }, 100);\n' +
' setInterval(() => {\n' +
' let configuration = '+ JSON.stringify(conf) +';'+
' fbAsyncInit(configuration);\n' +
' }, 5 * 60 * 1000);\n'
'</script>';
and we can receive as
window.fbAsyncInit = function (con) {
or we can pass call back function to html method and we do operation which is done in magic.js
Reference: http://api.jquery.com/html/#html-function
then we can return html accordingly.
I hope this will help you.

How to put id IS NOT NULL with escape varible ??/?

I tried to put 3 variations are included:
empty
version IS NOT NULL AND
version = ' + criteria.version + ' AND
I need use escape
Help please
this code is wrong, but for understanding I need like this:
function getCriteria(criteria){
var ver = '';
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ' + criteria.version + ' AND';
}
return mysql.getConnection((conn) => {
return conn.queryAsync('SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ? create_timestamp < "2017-02-16 13:34:40"', [ver]).then............
You could build the query text using regular string handling, but still use the parameterization for the case where you need it;
function getCriteria(criteria) {
var ver = '';
var parms = []
if(criteria.version == null){
ver = 'version IS NOT NULL AND';
}
else if(criteria.version > 0)
{
ver = 'version = ? AND';
parms = [criteria.version]
}
return mysql.getConnection((conn) => {
return conn.queryAsync(
'SELECT * FROM hlrlookup.hlrlookup ' +
'WHERE ' + ver + ' create_timestamp < "2017-02-16 13:34:40"', parms)
.then............

JS working in Chrome but not Firefox

This script stopped working in FireFox a couple of weeks ago, around the time I added an SSL certificate to the site. I've confirmed that SSL is being used everywhere, and I've tried disabling all recently installed plugins, to no avail.
I've looked at it with Web Console and don't see any errors there either - though I'm not very experienced with that.
I've also looked at other threads here about js working in Chrome but not FF, but none of the proposed solutions seem to apply to my script.
The problem is that the js is apparently not being called at all - it should show up between the introduction and the "share" graphic.
Any ideas?
This is the page where it should show up, between the text and the "share" graphic: Quiz
And this is the js file: Javascript
Here is the code:
$.each(questions, function (key, value) {
//console.log( key + ": " + value.question ); question = value.question;
qtype = value.qtype;
opts = value.opts;
answer = value.answer;
special = value.special; $('#quiz-form').append('<p> <br>' + parseInt(key + 1) + ") " + question + '</p>'); if (qtype == "radio")
{ opt_array = opts.split(','); for (i = 0; i < opt_array.length; i++)
{ $('#quiz-form').append('<p><input data-ftype="radio" type="radio" name="question_' + key + '" class="question_' + key + '" value="' + opt_array[i] + '"> ' + opt_array[i] + ' </p>'); }
} else if (qtype == "checkbox"}
else if (qtype == "checkbox")
{
opt_array = opts.split(',');
for (i = 0; i<opt_array.length;i++)
{
$('#quiz-form').append('<p><input data-ftype="checkbox" type="checkbox" name="question_' + key + '" class="question_' + key + '" value="'+ opt_array[i] + '"> ' + opt_array[i] + '</p>');
}
}
else if (qtype == "input")
{
$('#quiz-form').append('<p><input data-ftype="text" name="question_' + key + '" type="text" class="question_' + key + '" value="" style = "border:1px solid" ></p>');
} $('#quiz-form').append('<p><input name="answer_' + key + '" type="hidden" value="' + answer + '" class="answer_' + key + '" ></p>');
$('#quiz-form').append('<p class="special" id="special_' + key + '" ><strong>Correct answer(s): ' + answer + '</strong> » Explanation: ' + special + '</p>');
});
$('#quiz-form').append('<p>All done? Check your answers: <input name="submit" id="submit" type="button" value="Submit"></p>'); $('#quiz-form').append('<p>Want another chance? <input name="refresh" id="refresh" type="button" value="Start over"></p>'); $( "#quiz-form" ).on( "click", "#submit", function() {
quest_numb = questions.length;
user_answers = new Array();
real_answers = new Array();
for (i = 0; i <quest_numb;i++)
{
if ($("input[name ='question_" + i + "']").data('ftype')=='radio') { user_answers.push($(":input[type='radio'][name ='question_" + i + "']:checked").val()); } if ($("input[name ='question_" + i + "']").data('ftype')=='text') { user_answers.push($(":input[type='text'][name ='question_" + i + "']").val()); } if ($("input[name ='question_" + i + "']").data('ftype')=='checkbox') {
var chkArray = [];
$(".question_" + i + ":checked").each(function() {
chkArray.push($(this).val());
}); var selected = chkArray.join(',')
user_answers.push(selected); } real_answers.push($(":input[type='hidden'][name ='answer_" + i + "']").val()); // alert($(":input[type='text'][name ='question_"+i+"']").val());
}
points=0;
message='<div id="results">';
inc=1;
for(i=0;i<real_answers.length;i++) {
if (typeof user_answers[i]=='undefined' || user_answers[i]=='')
{ //message+='<p>'+parseInt(i+1) + ')' +' You didn't answer this question.</p>';
$('#special_'+i).text(i+inc+') '+'You didn\'t answer this question.');
$('#special_'+i).show();
$(":input[name ='question_"+i+"']").prop('disabled',true);
}
else if( user_answers[i].toLowerCase().trim()==real_answers[i])
{
points++;
//message+='<p>' +parseInt(i+1) + ')' +' Très bien !</p>';
$('#special_'+i).text(i+inc+') '+'Très bien !');
$('#special_'+i).addClass('correct');
$('#special_'+i).show();
} else
{
$('#special_'+i).text($('#special_'+i).text().replace(i+inc+') '+' ',''));
$('#special_'+i).prepend(i+inc+') '+' ');
$('#special_'+i).show();
}
}
message+='<p> Your score: ' + points + '/' + real_answers.length + '</p>';percent=points*100/real_answers.length;if(percent>=90)
{
message+='<p> Chapeau !</p>';
}
if(percent>=80 && percent<90)
{
message+='<p> Très bien !</p>';
}if(percent>=60 && percent<80)
{
message+='<p> Pas mal.</p>';
}if(percent>=40 && percent<60)
{
message+='<p> Houp ! Il faut étudier un peu plus.</p>';
}
if(percent<40)
{
message+='<p> Oh là là - il faut étudier !</p>';
}message+='</div>';
$('#quiz-form #results').remove();
$('#quiz-form').prepend(message);
$("html, body").animate({ scrollTop: 0 }, "slow");
});
$( "#quiz-form" ).on( "click", "#refresh", function() {
location.reload();
window.scrollTo(0,0);
});
});function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable){return pair[1];}
}
return(false);
}
There are numerous JS errors occurring throughout your code. First and foremost, you need to fix the insecure file references, since you are using SSL, so files like this will not load - either change it to relative paths or replace http with https:
<script src="http://www.feedblitz.com/js/tinybox2/tinybox.js" type="text/javascript">
If you are unsure how to view these errors in your browser, please refer to any of these articles:
https://developer.chrome.com/devtools
https://developer.mozilla.org/en/docs/Tools/Web_Console

Categories