#StackBounty: #sharepoint-online #document-library #jsom Create Link to a Document ( NewLink.aspx ) with JSOM

Bounty: 50

A customer has a added a content type called “New link to a document”, which let users add links to other documents, or any other site.
I’m not able to create new items of this content type programmatically using JSOM.
The file seems to be a template located at /_layouts/15/NewLink.aspx.

My current approach is:

  1. Download NewLink.aspx.
  2. Create new file, with contents for NewLink.aspx.
  3. Set URL and ContentTypeId on newly created file.

Creating the file works, but when opening the file I get an error about List not being set in query string.
One work-around is to create a dummy-file, and use this as template instead, this works perfectly (same approach as above).

I found this answer but I didn’t understand how it could help me.

Test code

My test-code (which I just run in Chrome console) looks like this:

const templateBase64 = await fetch(`/_layouts/15/NewLink.aspx`, {credentials: 'include'})
  .then(res => res.blob().then(blob => new Promise(resolve => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
  }))).then(dataUrl => dataUrl.slice(dataUrl.indexOf(',') + 1))

const ctx = SP.ClientContext.get_current()
const list = ctx.get_web().get_lists().getByTitle(listTitle)

const fileCreateInfo = new SP.FileCreationInformation()
const file = list.get_rootFolder().get_files().add(fileCreateInfo)

const fields = file.get_listItemAllFields()
fields.set_item('URL', 'http://google.com')
fields.set_item('ContentTypeId', contentTypeId)


ctx.executeQueryAsync(() =>  console.log('done'), (a, b) => console.log(b.get_message()))

listTitle is title of my document library, and contentTypeId I got from creating a link first and then checking what ContentTypeId it had in ListItemAllFields.


My app is actually a sharepoint-hosted app, so I can’t actually reach the file because I have to use GetFileByServerRelativeUrl, which won’t work against /_layouts/, but I can get this file locally from the app site, which seems to be identical. But before I try this I want to make it work on host web.

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.