Google Apps Script: Referencing the ActiveXObject - javascript

I wish to create an Excel object from within App Script. The following resource:
http://www.webdeveloper.com/forum/showthread.php?249479-Javascript-excel-object
shows how to do so using Javascript - I was therefore hopeful that I could use this code within Google Apps Script:
function xlTest() {
var xls = new ActiveXObject ( "Excel.Application" );
var newBook = xls.Workbooks.Add;
newBook.Worksheets.Add;
newBook.Worksheets(1).Activate;
}
When I try to run this function I get the error message:
ReferenceError: "ActiveXObject" is not defined
Hopefully I simply need to add a reference to ActiveXObject, if so could somebody please advise how I add a reference to ActiveXObject from Google Apps Script? Many thanks!

The question has nothing to do with Google Apps Script (or even JavaScript) and should not be tagged as such. You can't simply throw this code into Google Script Editor and expect things to work.
GAS is a JavaScript-based runtime that lives on Google servers, not in your browser. It doesn't have access to BOM (Browser Object Model) Furthermore, ActiveX is not supported in most browsers, including Microsoft Edge. Of course, VBA methods like Sheets.Add won't work for obvious reasons.
If you log the global object in Script Editor, you'll see all of its properties available to you as a developer.
In your browser, the properties of global object will be different:
Please take the time to go through GAS documentation and understand features & limitations https://developers.google.com/apps-script/

Related

How to use FileSystemObject to read file in JavaScript

I want to read a file with FileSystemObject. My code is as following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Read json</title>
</head>
<body>
<script type="text/javascript">
function readFile(filename){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var f1 = fso.OpenTextFile(filename, ForReading);
var text = f1.ReadAll();
f1.close();
return text;
}
myJSONText = "text.txt";
var myObject = readFile(myJSONText);//eval('(' + myJSONText + ')');
document.write(myObject.name);
</script>
</body>
</html>
First, let me repeat some comments above. I've never seen using ActiveXObject client side extolled as a thing that should be done.
Now, let me say I'm trying to learn how to do this myself. Here are some thoughts (and helpful links, see the bottom) on this question.
The general layout, according to "Much ADO about Text Files" on MSDN's scripting clinic column, is:
Create the object.
Create another object, using the first, that uses
a method of the first object (such as getting a file).
Do things to
the file.
Close the file.
How do you start? According to IE Dev Center (linked here), use an ActiveXObject in Javascript as follows:
newObj = new ActiveXObject(servername.typename[, location])
You've got that when you declare fso in your code. What about this "servername" thing, isn't the file accessed locally? Instead of "servername etc" you've put in Scripting.FileSystemObject. This is actually fine, if the HKEY_CLASSES_ROOT registry key on the host PC supports it (see ref above).
Once the ActiveXObject is successfully declared, and if the browser allows it (IE only), and if the end user agrees to any warnings that pop up ("An ActiveX control on this page might be unsafe to interact with other parts of the page..." etc), then the object allows you to use any of the methods associated with that object. That's where the power of the Windows Scripting FileSystemObject comes into play.
Any FileSystemObject (fso) method is now available to use, which as its name suggests, means file (and directory) interaction on the local machine. Not just reading, as your question is focused on, but writing and deleting as well. A complete list of methods and properties is available at MSDN here. After being used, close out the file using the .close() method.
So, this is dangerous for obvious reasons. But what wasn't obvious to me at first was that these interactions with the filesystem may happen invisibly. There is a good chance that whatever you do, from reading a file to deleting a directory tree, no warnings or command prompts will come up to let you know what's happening because of your few lines of code.
Let me finish by commenting on the last bits of code above. Using JSON in conjunction with data pulled from the FileSystemObject provides a great way to allow JavaScript interaction (JSON .parse and .stringify come immediately to mind). With this, data could be stored locally, perhaps as an alternative to HTML5 local storage (ref this SO thread, which goes more in-depth with this concept, and another SO question I raised about this here).
Here are some links for further reading:
IE Dev Center, JavaScript Objects, ActiveXObject
MSDN JScript Windows Scripting (including FileSystemObject methods, etc)
MSDN Scripting Clinic (older articles, many broken links, but stil a lot of good info on this stuff)

WScript.Sleep() ~ WSScript is undefined

I'm trying to follow some example code from microsofts mdn site..
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");
while (oExec.Status == 0)
{
WScript.Sleep(100);
}
WScript.Echo(oExec.Status);
I'm currently writing a javascript/JScript to run a few batch commands. Everything works fine if I don't use WScript.Sleep(). However, If i try to use it, to prevent locking up the browser, i'm getting an error that WScript is not defined.
I figured that I needed to define it myself. However, I have been searching mdn website all day with no luck. This is my first time using any "windows only" products I could be coompletly overlooking something.
If you want to see the documentation I'm looking through it is located here.
http://msdn.microsoft.com/en-us/library/ateytk4a(v=vs.85).aspx
Any help is greatly appreciated.
Thanks,
Freddy
WScript is an object that is defined when the Javascript is run within the Windows Script Host, aka WSH. The object is not available within the Javascript engine in a web browser.
If you are really trying to produce "batch like" files, then you don't need a browser, and I'd say you probably don't want a browser. You can write your code into a .js file and just run it from the cmd.exe prompt or Explorer window with a double-click.
Change the script language from JavaScript to JScript

Using third-party JS libraries in Mozilla Add-On SDK

I'm starting a new project (Firefox add-on) and I'd like to try using behavior-driven development. I particularly like the Jasmine BDD library. However, I can't find a good way how to use a framework such as Jasmine in the Add-On SDK.
One problem is that Jasmine needs setTimeout (and similar) functions to be specified on the global object, whereas Add-On SDK exports those using "timers" module. But let's say I tweak Jasmine to get those object from "timers" (or add the the methods exported by timers to the global object).
The bigger problem is that I don't know how to actually run the tests. There is a test directory generated by the SDK, however, there's no window or document object there to allow me to see the output (and I'd really like to see the fancy HTML output). I guess I could create a content script that would modify the page, but then I can't access (test) the background script.
Have you ever faced this before? Is there any recommended way how to deal with that?
Thanks!
Tomas
You can use the Add-on SDK windows API to open a new window to run your tests in. You should be able to load the Jasmine script(s) with the subscript loader and set window and document to whatever you want in the scope of that subscript:
var windows = require("windows").browserWindows;
windows.open({
url: "about:blank",
onOpen: function(window) {
var script;
var scriptLoader = Cc["#mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
scriptLoader.loadSubScript(subscriptSpec, script);
script["window"] = window;
script["document"] = window.document;
// ... run your tests here by calling script.someFunc() ...
}
});
Update: Further research shows that the browserWindows are actually special wrappers that don't give you access to the content window. You might try getting a window/document from a hidden frame. That's the only way I can see to get access to an HTML document from privileged code.

Outlook 2010: How to compose e-mail from VBScript/JScript

I have some JScript code I have been using for a few years which is able to read an XML file and open an Outlook compose window with the to/cc/subject fields prepopulated and files pre-attached based on the XML data. The user can then attach more files, make any corrections and send the e-mail. The core part of the code uses CDO to create the new message:
var ol = WScript.CreateObject("Outlook.Application");
var msg = ol.CreateItem(olMailItem);
Unfortunately I have just discovered this no longer works with Outlook 2010 64-bit as CDO is no longer supported. The suggestion from Microsoft is to update your applications to use the Outlook object model instead, but I can't find any examples at all of how I might use the Outlook object model to open a compose window from either VBScript or JScript. All the "VB" examples on MSDN produce syntax errors when run through the VBScript interpreter.
Can anyone point me to any short examples demonstrating how to interface with Outlook 2010 using either VBScript or JScript?
EDIT: Just realised the problem is that I'm using MAPI.Session to adjust attachment properties and this is what's failing. I guess I need to find what this has been replaced by:
var oSession = WScript.CreateObject("MAPI.Session");
oSession.Logon("", "", false, false);
var oMsg = oSession.GetMessage(strMsgID);
var oAttachFields = oMsg.Attachments.Item(i+1).Fields;
...
Ok, turns out most of the MAPI.Session stuff has been merged in with the actual objects, which are still accessible using the first bit of code in my post ("Outlook.Application"). I was only using the MAPI.Session stuff to hide image attachments (so they can be shown inline in the message body, and not as files attached to the e-mail) but this now seems to be incorporated automatically.
So all I actually had to do was remove the MAPI.Session stuff and then everything started working. I will post a link to the code shortly in case anyone else finds it useful.
EDIT: Here is the code on GitHub if anyone is after a relatively simple example.

Tutorial for using JavaScript on a Desktop

I need to do some scripts in java script.
I am working on it but couldn't find a few solutions to a few problems.
First of all I need a GOOD tutorial, but not for an internet page but for a DESKTOP script.
Things couldn't find out like :
1) I wanted a simple message box in order to debug my program, I used:
var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
2) Couldn't find how to open a file
Based on your comments, I guess that you are attempting to run a JavaScript file directly on Windows. Double-clicking on a .js file in windows will (probably) run it in Windows Script Host.
The prompt() function will not work this way, since WSH provides a completely different API than browser-embedded engines.
The following code should accomplish your intentions. However if you want anything more than a simple popup, HTAs are the only way to do complex GUIs with JScript on the desktop.
var fso, ws, ts;
fso = new ActiveXObject('Scripting.FileSystemObject');
ws = WScript.CreateObject('WScript.Shell');
var ForWriting= 2;
ts = fso.OpenTextFile('foo.txt', ForWriting, true);
ts.WriteLine(new Date().getTime());
ts.Close();
ws.Popup('Wrote to file!');
var ForReading= 1;
ts = fso.OpenTextFile('foo.txt', ForReading, false);
var fileContents = ts.ReadLine();
ts.Close();
ws.Popup('The file contained: ' + fileContents);
WScript.Quit();
I have to ask: why is JavaScript the right tool for the job? Why not use a scripting language intended to be used this way, such as Python, Ruby, Lua, ... etc?
If you are using Microsoft's JScript (and it sounds like you are), look to the MSDN web site for help. The page here looks fairly good. Google can also help with that.
Assuming you don't mind using Java, you could also use the Mozilla Rhino shell. But it doesn't look like there is a standard way of reading from the console in JavaScript. (presumably since this is not something typically required in a JavaScript application...) The built in JavaScript functions in the shell seem fairly basic, but you can read a file.
There area also examples of using Rhino, which may be helpful. You can interface with the Java API to do whatever else you need to do.
Edit: I wrote this answer a long time ago; today I would use node.js. See their learning page.
The latest prerelease of Opera acts as a runtime for JS applications.
They have tutorials describing how to use it.
I used: var name = prompt("What is your name","Type Name Here");
When running it I get error of "Object expected"
Presumably your runtime doesn't implement prompt that in a way that is compatible with those arguments.
2) Couldn't find how to open a file
This depends on the runtime you use. JS itself doesn't have anything built in to read files (or display a prompt). You need an environment that provides those objects.

Categories

Resources