Created
March 16, 2021 12:39
-
-
Save anoopt/1b4d7ebc6cd2c930864afaa0e48c988d to your computer and use it in GitHub Desktop.
Update links in the SharePoint modern "Quick Links" webpart using PnP JS and SP editor extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { sp } from "@pnp/sp"; | |
| import "@pnp/sp/webs"; | |
| import "@pnp/sp/lists"; | |
| import "@pnp/sp/items"; | |
| const sectionPosition = 1; | |
| const columnPosition = 1; | |
| const webPartPosition = 3; | |
| const updateQuickLinks = async (title, fileRef) => { | |
| let savePage = false; | |
| console.log(`%c Processing page ${title} - ${fileRef}`, 'color: yellow'); | |
| const page = await sp.web.loadClientsidePage(fileRef); | |
| const section = page.sections[sectionPosition]; | |
| const column = section && section.columns[columnPosition]; | |
| const part = column && column.getControl(webPartPosition); | |
| let links = part && part.json.webPartData.serverProcessedContent.links; | |
| const items = part && part.json.webPartData.properties.items; | |
| if (links && items && items.length > 0) { | |
| console.log(`%c Links are %o`, 'color: yellow', links); | |
| items.forEach((item, index) => { | |
| let itemProperty = `items[${index}].sourceItem.url`; | |
| let itemLink = links[itemProperty] | |
| if (itemLink && itemLink.substr(itemLink.lastIndexOf('.') + 1) === "aspx") { | |
| console.log(`%c Link ${index} ${itemLink}`, 'color: yellow'); | |
| part.json.webPartData.serverProcessedContent.links[itemProperty] = itemLink.replace("https://ABC/", "https://XYZ/"); | |
| savePage = true; | |
| } | |
| }); | |
| } | |
| if (savePage) { | |
| console.log("%c Saving page with updated links", 'color: yellow'); | |
| await page.save(); | |
| } | |
| console.log(`%c Completed processing page ${title} - ${fileRef}`, 'color: green'); | |
| } | |
| (async () => { | |
| const allPages = await sp.web.lists.getByTitle("Site Pages").items | |
| .select("Title", "FileRef", "ContentTypeId") | |
| .filter("ContentTypeId eq '0x010100------------'") | |
| .getAll(); | |
| console.log(`%cBegin`, 'color: orange') | |
| for (const page of allPages) { | |
| if (page["FileRef"].indexOf("Templates") < 0) { //TODO: See if this can be done in the query itself | |
| await updateQuickLinks(page["Title"], page["FileRef"]); | |
| } | |
| } | |
| console.log(`%cEnd`, 'color: green'); | |
| })().catch(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment