Search code examples
javascriptms-wordoffice-interopactivexobject

Microsoft Word - Insert text from JavaScript/JScript ActiveX


I want to use JavaScript (on a web page) to insert some text into a Microsoft Word document. The Documentation has sample code for VB and C#, but not for JavaScript (JScript). I've been able to figure out a lot of it using code samples as seen here, but certain lines are messing me up.

Here's what I've got so far:

var retText;

var wshShell = new ActiveXObject("WScript.Shell");
var wordApp = new ActiveXObject("Word.Application");
wordApp.Documents.Add();

if (wordApp.Application.Options.Overtype) {
    wordApp.Options.Overtype = false;
}

But when it comes to this line (in C#), I can't quite get at how to translate it:

if (currentSelection.Type == Word.WdSelectionType.wdSelectionIP) 

currentSelection.Type can be translated to wordApp.Selection.Type in my code above, but I'm not sure what to do with Word.WdSelectionType.wdSelectionIP.

Some failed attempts:

alert(wordApp.WdSelectionType); //undefined
alert(new ActiveXObject("Word.WdSelectionType"); //errors out
alert(wordApp.ActiveDocument.WdSelectionType); //undefined    

Solution

  • I don't think COM enums are accessible from Javascript.

    Instead, you can use the constant's numeric value, which you can find in the VBA object browser.
    For readable code, you can make a Javascript variable holdign the value instead of just writing a number.