Creating Documents from Templates with JavaScript

We can decide whether documents within a document library should open in the Web App (within the browser) or in the client’s local Microsoft Office application in Library Settings -> Advanced Settings.OpenInBrowser

Whilst SharePoint obeys this setting when opening existing documents, it ignores it when creating new ones.  If the client’s Microsoft Office application is available, SharePoint will use it to create documents, regardless of the library or site collection settings.


Creating Documents via the Web App

Fortunately, we can use the JavaScript in SharePoint’s core.js to create documents within the Web App, regardless of the client’s local Office installation…

CoreInvoke('createNewDocumentWithRedirect2', event, '[template URL]', 'http://[server]' + (ctx.rootFolder == '' ? ctx.listUrlDir : decodeURIComponent(ctx.rootFolder)), 'SharePoint.OpenDocuments', false, 'http://[server]/[subsite]/_layouts/15/CreateNewDocument.aspx?id=[escaped template URL]', false, 1, '[web app]');

For example, to open the standard document library template in the Shared Documents document library on server SharePointDev01…

CoreInvoke('createNewDocumentWithRedirect2', event, 'http://SharePointDev01/Lists/Shared%20Documents/Forms/template.dotx', 'http://SharePointDev01' + (ctx.rootFolder == '' ? ctx.listUrlDir : decodeURIComponent(ctx.rootFolder)), 'SharePoint.OpenDocuments', false, 'http://SharePointDev01/_layouts/15/CreateNewDocument.aspx?id=http%3a%2f%2fSharePointDev01%2fLists%2fShared%20Documents%2fForms%template.dotx', false, 1, 'ms-word');


Creating Documents via the Client’s Microsoft Office Application

Similarly, we can just as easily create documents within the client’s Office application, assuming it’s available…

CoreInvoke('createNewDocumentWithProgID', '[template URL]', 'http://[server]' + (ctx.rootFolder == '' ? ctx.listUrlDir : decodeURIComponent(ctx.rootFolder)), 'SharePoint.OpenDocuments', false, '[web app]');

To give the same example as above…

CoreInvoke('createNewDocumentWithProgID', 'http://SharePointDev01/Lists/Shared%20Documents/Forms/template.dotx', 'http://SharePointDev01' + (ctx.rootFolder == '' ? ctx.listUrlDir : decodeURIComponent(ctx.rootFolder)), 'SharePoint.OpenDocuments', false, 'ms-word');


Additional Points

The available values for the application parameter are 'ms-word', 'ms-powerpoint', 'ms-onenote' and 'ms-excel'.

The following JavaScript evaluates to be the site-relative URL of the document library (or subfolder if applicable) in the current context.

ctx.rootFolder == '' ? ctx.listUrlDir : decodeURIComponent(ctx.rootFolder)

That contextual reference is great for use within a web part on a document library’s list view page.