Whenever you create a SharePoint hosted app, it will create an app on your host web. In Appweb, you can see that the site logo is the default SharePoint logo and even if we change the app icon in the Appmanifest.xml file, it will change the logo of the app but not the app website logo URL and we can't change the Logo using SiteSettings as it's not accessible in Appweb. So generally, developers change the image src tag attribute at runtime. But we can set the SiteLogoUrl property of Appweb using REST API or JSOM.
So today, we will see how to implement it using REST API.
- Create a SharePoint Hosted App using VS and target it to the developer site which will add a default.aspx page.
- Add a logo of your appweb into the image folder.
- Open App.js or you can create a new JS file and and copy the below code.
- Give reference to the script file which you have created to the pages.
- 'use strict';
- ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");
-
- //to get query string parameters
- function getParameterByName(name, url) {
- if (!url) url = window.location.href;
- name = name.replace(/[\[\]]/g, "\\$&");
- var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
- results = regex.exec(url);
- if (!results) return null;
- if (!results[2]) return '';
- return decodeURIComponent(results[2].replace(/\+/g, " "));
- }
-
- //On document ready get the current site logo
- $(document).ready(function () {
- var SPAppWebUrl = getParameterByName("SPAppWebUrl");
- if (SPAppWebUrl) {
- getSiteLogoUrl(SPAppWebUrl);
- }
- });
-
- //Using web rest api end post and updating the site logo url
- function changeSiteLogo(weburl) {
- var imageUrl = weburl + "/Images/News.png";
- var webData = {
- '__metadata': { type: 'SP.Web' },
- 'SiteLogoUrl': imageUrl
- }
- $.ajax({
- url: weburl+ "/_api/web",
- type: "POST",
- data: JSON.stringify(webData),
- headers: {
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "accept": "application/json;odata=verbose",
- "content-type": "application/json;odata=verbose",
- "X-HTTP-Method": "MERGE"
- },
- success: function (data) { console.log("App web logo changed") ;
- window.location.href = window.location.href;
- },
- error: function (data) { alert("errrr")}
- });
- }
-
- function getSiteLogoUrl(weburl) {
- //Logo which you want to assign
- var imageUrl = weburl + "/Images/News.png";
- $.ajax({
- url: weburl + "/_api/web?$select=SiteLogoUrl",
- type: "GET",
- headers: {
- "accept": "application/json;odata=nometadata",
- },
- success: function (data) {
- var SiteLogoUrl = data.SiteLogoUrl;
- //if site logo is already changed no need to apply changes, if not we have to change
- if (SiteLogoUrl != imageUrl) {
- changeSiteLogo(weburl);
- }
- },
- error: function (data) { alert("errrr") }
- });
- }