Copy Modern Page Within The Folder Using JSOM

In this blog, we are going to discuss how to copy a modern page within the same folder of a site collection. You can do it manually or programmatically. Follow the below steps to copy a client-side page.

How to Copy a page manually

  1. Go to your site’s Site Pages. Select a page.
  2. Click on “Three dots” to present the right side of a page as shown below. Then click on “Copy to”.

3. A pop-up will open, select the Folder, then click on “Copy here”.

How to Copy a Modern page programmatically using JavaScript

Follow the below JavaScript code to copy a modern page in the same folder of a site collection.

var fileLibName = “home.aspx”;
var newFileName = “Test.aspx ";
var fileContentUrl = < enter your siteUrl > +"/_api/web/GetFileByServerRelativeUrl('" + fileName + "')/$value";
var restUrl = < enter your siteUrl > +"/_api/web/GetFolderByServerRelativeUrl('" + folderName + "')/Files/Add(url='" + newFileName + "',overwrite=true)";
$(function() {
    $.ajax({
        url: < enter your siteUrl > +"/_api/contextinfo",
        type: 'POST',
        processData: false,
        headers: {
            "Accept": "application/json; odata=verbose",
            "X-RequestDigest": $('#__REQUESTDIGEST').val(),
        },
        success: successHandler,
        error: errorHandler
    })
})

function successHandler(data, textStatus, jqXHR) {
    var digest = data.d.GetContextWebInformation.FormDigestValue;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', fileContentUrl, true);
    xhr.setRequestHeader('binaryStringResponseBody', true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        if (this.status == 200) {
            var arrayBuffer = this.response;
            $.ajax({
                url: restUrl,
                method: 'POST',
                data: arrayBuffer,
                processData: false,
                headers: {
                    'binaryStringRequestBody': 'true',
                    'Accept': 'application/json;odata=verbose;charset=utf-8',
                    'X-RequestDigest': digest
                }
            }).done(function(postData) {
                Console.log(“Copied successfully”);
            }).fail(function(jqXHR, errorText) {
                Console.log(“Error”);
            });
        }
    }
    xhr.send();
}

function errorHandler(xhr, ajaxOptions, thrownError) {
    var msg = "FAILED: " + xhr.responseText;
    console.log(msg);
}

The original page

The copied Page

Conclusion

We can conclude that this copy feature will help a user copying a page with all the contents present inside the page. Hence, we have done it programmatically to make this easier and more effective.