I'm attempting to convert some VBScript to javascript, but I doubt it's possible because it seems to be specific to MS apps and code. I'd like help with either of the two possible outcomes: a) actually converting the code to javascript, or b) demonstrating that converting it to javascript is currently not possible.
The specific VBScript statements that I consider too MS-specific are:
set oExcel = CreateObject("Excel.Application")
set oBook = oExcel.Workbooks.Add
oBook.HTMLProject.HTMLProjectItems("Sheet1").Text = sHTML
oBook.HTMLProject.RefreshDocument()
oExcel.Visible = True
oExcel.UserControl = True
Has anyone interfaced javascript and Excel well enough for a solution to exist?
Sure like this:-
var excel = new ActiveXObject("Excel.Application")
var book = excel.Workbooks.Add()
//The line below doesn't work in Excel 2007
// book.HTMLProject.HTMLProjectItems["Sheet1"].Text = sHtml
var sheet = book.Sheets("Sheet1")
sheet.Range("A2").Value = "Hello World"
excel.Visible = true
excel.UserControl = true
You can do this only with JScript, not JavaScript- this will show you how. This may be fine if you are using only IE.
Related
I hope this is the right place for this question. I have been trying to set up a simple document that calculates fields based on other fields with the same document. I am attempting to create a list of variables to make scripting faster. right now my document script looks like this
var lv = this.getField("Level").value;
var s = this.getField("StrB").value;
var d = this.getField("DexB").value;
var c = this.getField("ConB").value;
var int = this.getField("IntB").value;
var w = this.getField("WisB").value;
var ch = this.getField("ChaB").value;
var ss = this.getField("Str").value;
var ds = this.getField("Dex").value;
var cs = this.getField("Con").value;
var ints = this.getField("Int").value;
and so on.
This is an example of a script using these variables
{
event.value = strBonus + pb;
}
This returns nothing. Not even a warning. I double-checked my spelling and names. I am sure this is a formatting issue as I am a novice and don't fully understand the language. Any help would be greatly appreciated! Thank you for your time in reading this.
When you define and initialise a variable in a document level script, they get the field value at that time (and that's normally blank).
So, in order to simplify things, define the variables as Field Objects, such as in
var lv = this.getField("Level") ;
In the calculation, you will then retrieve the field value as, for example, in
var lv1 = lv.value * 5 ;
And that should do it.
About documentation: You will need the Acrobat JavaScript documentation, which is part of the Acrobat SDK documentation, downloadable from the developer section of the Adobe website.
Background
I have a load of Applescripts(AS) which designers use with InDesign that help process the workflow for production. There is a great deal of OS interaction that the AS does that the JavaScript can not, so moving away from AS is not possible.
Due restrictions I am unable to install pretty much anything.
I am unable to update anything. Script Editor and ExtendScript Tool Kit are what I have to work with.
Operating Environment:
OS X 10.8.5 &
Adobe CS6
How it works
User preferences are saved as Properties in local Applescripts saved in the user's documents folder.
###property grabber.scpt
set mypath to path to documents folder
set mypropertiesfile to ((mypath & "myproperties.scpt") as string)
set thePropertyScript to load script file mypropertiesfile
set designerinitials to (designerinitials of thePropertyScript) ETC...
Some of the properties are AS lists.
Why I need JS?
I'm making palettes and would prefer to use the ScriptUI rather than do it all in AS like this:
set dlgRef to make dialog with properties {name:"User Settings", can cancel:true, label:"Dialog Label"}
The string the AS hands off to the JS is this:
{"myname",{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"},{firstvalue:"test2", secondvalue:"val2", thirdvalue: "val3"}}
These are not lists, but text...
The JS
myAppleScript = new File("valid_path_to/property grabber.scpt");
var myreturn = app.doScript(myAppleScript, ScriptLanguage.applescriptLanguage);
var myname = myreturn[0];
var firstlist = myreturn[1];
var secondlist = myreturn[2];
ExtendScript data browser shows:
firstlist = {firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}
It is not an array...
I have tried using https://github.com/KAYLukas/applescript-json
to json encode the lists, but the same result.
firstlist = [{firstvalue:"test", secondvalue:"val2", thirdvalue: "val3"}]
I have also made it much simpler with just
firstlist = {"test","val2","val3"}
Still the JS treats it as a string and not an array.
Any ideas what I need to do or am doing wrong? I hope it simple and I feel stupid if I get an answer...
Glad you have something that works, but if you're passing text to ExtendScript, why not format it on the AS side to be ExtendScript-friendly, like ['firstvalue', 'secondvalue', 'thirdvalue"'] --but this would be a string in AS, like
--in AS:
"['firstvalue', 'secondvalue', 'thirdvalue"']"
Then, in ExtendScript, if that's in a variable, like, myData, you can do (as I just did in ExtendScript Toolkit):
//in JS:
myArray = eval(myData);
I know using eval() is evil in web work, but for ExtendScript stuff, it can be very useful.
I hate finding an answer after I take the time to post an elaborate question.
https://stackoverflow.com/a/14689556/1204387
var path = ((File($.fileName)).path); // this is the path of the script
// now build a path to another js file
// e.g. json lib https://github.com/douglascrockford/JSON-js
var libfile = File(path +'/_libs/json2.js');
if(libfile.exists)
$.evalFile(libfile);
Like Neo learning Kung Fu, it suddenly went, "Whoa, I know JSON!"
var firstlist = JSON.parse(myresult[1]);
Gives me workable objects
doScript can pass script args to one language to another. Here is a snippet inspired from the doc:
var aps = "tell application \"Adobe InDesign CC 2014\"\
tell script args\
set user to item 1 of {\"John\", \"Mike\", \"Brenda\"}\
set value name \"user\" value user\
\"This is the firest AppleScript script argument value.\"\
end tell\
end tell"
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var user = app.scriptArgs.getValue("user");
alert( user+ "from JS" );
I don't think script args would return anything else than strings even if those could represent any kind of value. However a string can be easily turned into an array with a split method like this :
var aps = "set ls to {\"john\", \"mark\"}\
set n to count of items of ls\
set str to \"\"\
repeat with i from 1 to n\
set str to str & item i of ls\
if i < n then\
set str to str & \",\"\
end if\
end repeat\
tell application \"Adobe InDesign CC 2014\"\
tell script args\
set value name \"str\" value str\
end tell\
end tell";
app.doScript(aps, ScriptLanguage.applescriptLanguage);
var str = app.scriptArgs.getValue("str");
var arr = str.split(",");
alert( "Item 1 of APS list is \""+arr[0]+ "\" in the JS context" );
The idea is to flatten the APS list into a comma separated string that will be later splitted in the javascript context to turn it into an array.
Hey guys quick question what is the best approach on converting Model to Javascript.
I tried using this
#{
var arr = new string[3];
arr[0] = "1";
arr[1] = "2";
arr[2] = "3";
var jason = JsonConvert.SerializeObject(Model);
}
<script type="text/javascript">
var string = '#jason';
var variable2 = jQuery.parseJSON(string);
alert(variable2.Id);
</script>
as you can guess it did not work, I look through the sample of jQuery which should work but I am not sure if it is compatible with JsonConvert of .net
Its my first time on programming in the client side so this is quite a simple question but I tried looking the answer from the net. Mostly I see are uber complicated answers and at least 3 and higher old so I am guessing there should be an easier way to do this now?
I feel like this needs an answer because it's the number 2 result from google and has been viewed over 200 times, and as stated by the OP every other answer is generally long and/or convoluted. But the simplest answer is:
Javascript added to your aspx page:
<script type="text/javascript">
var myObject = <%=JsonConvert.SerializeObject(MyNetObject)%>;
</script>
The key bit being that your output of HTML looks as follows:
<script type="test/javascript">
var myObject = {"Prop1":"value1","Prop2":"Value2"};
</script>
Javascript natively handle JSON so you don't need to reparse anything on the client side. If the object is properly serialized it will be recognized without further conversion (this includes lists and object properties).
In the example provided in the OP the resultant Javascript object would be a simple array. So access to the elements on the client side would be:
alert(variable2[0]), alert(variable2[1]), alert(variable2[2])....
In order to provide the Javascript property calling functionality that OP is trying to do on the client side would require the following on the server side:
var json = JsonConvert.Serialize(new { ID1 = 1, ID2 = 2, ID3 = 3 });
In which an object with Named properties is serialized into the page.
when i use user defined tags with uppercase node like "<ABC> test </ABC>" in ckeditor .On clicking source, it gets displayed as "<abc> test </abc>".please help me to get the expected output , which should be <ABC> test </ABC> and please guide me where the code should be modified.Thanking you
(Continued from comments) I propose post-processing the content and not trying to bend CKEditor to produce Case Sensitive output.
I don't know your languages or your architecture, but if you get the data from CKEditor with getData(), you can do something like this if you want to do the conversion in the client side:
// Javascript
var i = CKEDITOR.instances.editor1;
var d = i.getData();
var correctData = d.replace(/<abc/ig, '<ABC');
In the backend you can do something similar
// C# (untested)
string result = Regex.Replace(
htmlStringFromAJAX,
RegEx.Escape("<abc"),
RegEx.Escape("<ABC"),
RegexOptions.IgnoreCase
);
// PHP (untested)
$result = str_ireplace("<abc", "<ABC", $htmlStringFromAJAX);
(I hope you either have just this one abc tag or a small static amount of tags - if not, this will be a very annoying solution to maintain.)
Do you guys know of a solid library/function in Javascript to clean user input.
Mainly for preventing XSS attacks and the sort.
It would be a plus if the said library had the option of allowing certain tags etc.
EDIT: I'm using node.js on the backend. That's why I need a javascript library for that sort of thing.
People are recommending a part of Google Caja here:
Preventing XSS in Node.js / server side javascript
But I was just hoping to get more options.
I use node-validator by chriso.
Example
var check = require('validator').check,
sanitize = require('validator').sanitize
// Validate
check('test#email.com').len(6, 64).isEmail(); //Methods are chainable
check('abc').isInt(); //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt(); //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);
// Sanitize / Filter
var int = sanitize('0123').toInt(); //123
var bool = sanitize('true').toBoolean(); //true
var str = sanitize(' \s\t\r hello \n').trim(); //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a'); //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode(); //'<a>'
This is the equivalent of the PHP strip_tags function in Javascript. phpjs.org comes in handy for this kind of situations.
http://phpjs.org/functions/strip_tags:535
For this purpose I use DOMPurify, it is good enough and fast library. The examples below from official documentation.
DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x">
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
DOMPurify.sanitize('<p>abc<iframe/\/src=jAva	script:alert(3)>def'); // becomes <p>abcdef</p>
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
DOMPurify.sanitize('<UL><li>click</li></ul>
You can find more by following this URL.