Get Publishing Page Layout HTML File Contents via JavaScript in SharePoint 2013

Web Design & Development

I’m working on a project where I need to grab the contents of a Page Layout HTML file on a publishing site via JavaScript. The obvious solution would be to use a GET request via AJAX (I’m using jQuery here). The file contents are plain text with no binary data, so it should be a straightforward task:

$.ajax({
    url: "http://server/_catalogs/masterpage/custom-page-layout.html",
    method: "GET"
}).done( function( data ) {
    console.log( data ); // Preview page HTML contents, boo!
});

Unfortunately, SharePoint redirects this request to the preview page for the page layout, so ultimately the AJAX request returns the HTML data for “http://server/_layouts/15/previewwithstatus.aspx?Url=%2F_catalogs%2Fmasterpage%2Fcustom-page-layout%2Ehtml” which is not what I need.

Fortunately the REST API offers a way to work with files and folders. In this case, I simply changed the url parameter for my AJAX request to use the API endpoint instead of directly accessing the file:

$.ajax({
    url: "http://server/_api/web/GetFileByServerRelativeUrl('/_catalogs/masterpage/custom-page-layout.html')/$value",
    method: "GET"
}).done( function( data ) {
    console.log( data ); // HTML contents, yay!
});

This returned the file contents without redirecting the GET request to the preview page.