Redirect URL to different page in SharePoint before rendering using jQuery

Ahamed Fazil Buhari
 
Senior Developer
May 30, 2018
 
Rate this article
 
Views
6616

Hello everyone,

In this article we will see how to redirect to different URL from SharePoint. Here we are going to redirect to different URL before anything renders on the page. In this scenario we need to redirect to different page if the user clicks or provide URL of specific SharePoint list, also we have added queryString functionality which helps admin to stay on the same page without navigation.

Consider we have list named Test in SharePoint – https://fazilbuhari.sharepoint.com/sites/demo/Lists/Test/ and if I provide this link in the browser then it should navigate to https://outlook.com without rending anything from SharePoint. And if the URL is provided as https://fazilbuhari.sharepoint.com/sites/demo/Lists/Test?admin then it will not redirect instead it will renders the actual page.

To achieve this, we updated the master page since we need to load this script before anything renders on the page. (Make sure to have backup of master page for safety J). My SharePoint site is using seattle master page.

Open the SharePoint Designer, go to Master Pages and right click on seattle.html and select ‘Edit File in Advanced Mode’

clip_image002

 

 

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
 </script>
 <script>
 //<![CDATA[
 var relativeURL = document.location.href.split("?")[0];
 var targetURL = "https://outlook.com";
 if (
   relativeURL &&
   relativeURL.search("NewForm.aspx") === -1 &&
   relativeURL.search("DispForm.aspx") === -1 &&
   relativeURL.search("EditForm.aspx") === -1
 ) {
   var listName = relativeURL.toLowerCase().split("/lists/")[1];
   if (listName) {
     listName = listName.split("/")[0];
     if (listName === "Test") {
       var queryString = document.location.href.split("?")[1];
       if (queryString) {
         var params = queryString.split("&");
         var isRedirect = true;
         for (var i = 0; i < params.length; ++i) {
           var keyValue = params[i].split("=");
           if (keyValue[0] === "admin") {
             isRedirect = false;
           }
         }
         if (isRedirect) {
           window.location.replace(targetURL);
         }
       } else {
         window.location.replace(targetURL);
       }
     }
   }
 }
 //]]>
 </script>
 

 

Also we are not redirecting for NewForm, EditForm and DispForm. You can update the script as per your requirement.

clip_image004

Happy Coding

Ahamed

Author Info

Ahamed Fazil Buhari
 
Senior Developer
 
Rate this article
 
Ahamed is a Senior Developer and he has very good experience in the field of Microsoft Technologies, especially SharePoint, Azure, M365, SPFx, .NET and client side scripting - JavaScript, TypeScript, ...read more
 

Leave a comment