Is it possible to set the Welcome Page of a SubSite using only Javascript? I'm looking to create an Onclick Event that does this. Anything would help.
2 Answers
Here is the code to set the welcome page:
var context = null;
var web = null;
var rootFolder = null;
var welcomePage = 'SitePages/Home.aspx';
SetWelcomePage();
function SetWelcomePage()
{
context = new SP.ClientContext.get_current();
web = context.get_web();
rootFolder = web.get_rootFolder();
context.load(web);
context.load(rootFolder);
rootFolder.set_welcomePage(welcomePage);
rootFolder.update();
context.executeQueryAsync(onSuccess, onFail);
}
function onSuccess()
{
console.log('Welcome Page Set!');
}
function onFail()
{
console.log('Error!');
}
-
Did you mean to create the function
SetWelcomePage, instead of calling it? You also don't need to callnewwhen callingSP.ClientContext.get_current(). You don't need toloadthe variables. Why not just do something like this: gist.github.com/eirikb/eec211d3abc19cfe142c1c5753c19303 (untested)?eirikb– eirikb2016-05-25 13:08:56 +00:00Commented May 25, 2016 at 13:08
The answer provided by Ahmed Mahmoud is not wrong (and should perhaps be marked accepted), calling set_welcomePage on SPWeb RootFolder is the correct approach.
But the provided examples doesn't run, so I have decided to provide a couple of alternative code examples.
Note, they use features from ES6, and the variable subWeb refer to server-relative or absolute URL as of OP's question.
JSOM
const context = new SP.ClientContext(subWeb);
const rootFolder = context.get_web().get_rootFolder();
rootFolder.set_welcomePage('SitePages/NewHome.aspx');
rootFolder.update();
context.executeQueryAsync(
() => console.log('Done'),
(a, b) => console.error(b.get_message()));
REST
const digest = document.getElementById('__REQUESTDIGEST').value;
fetch(`${subWeb}/_api/Web/RootFolder`, {
credentials: 'include',
method: 'post',
body: JSON.stringify({WelcomePage: 'SitePages/NewHome.aspx'}),
headers: {
'X-HTTP-Method': 'MERGE',
'Content-Type': 'application/json',
'X-RequestDigest': digest
}
});