CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: url

Bypass all custom jslink

bypasscustomjslink-001

Client Side Rendering (CSR) and jslink are great for customizing lists and forms in SharePoint. In my current project we use it a lot of it. A disadvantage of that path, although, is that it might occur javascript errors, during the development phase, but also in production. We do, of course, our best to leverage the best jslink code, but unfortunately we have to live with the fact that errors can occur, especially when we use it for NewForm, EditForm, DisplayForm and View (in list and grid).

If an error occurs, it won’t stop the rest of javascript (it is wrapped in try and catch by SharePoint), but the fields will still not function as intended. It can also be some “corrupt” or old data in the field value that will “break” the jslink code.

I would like to suggest one little fix, an idea I’ve come up to in my jslink-heavy project:

Use a custom url parameter to stop all custom jslink execution.

The query string parameter can be called bypasscustomjslink=true

In every custom jslink, start with this line of code:

That’s it. If you have this in place, you can just manually add this to your url in browser:

?bypasscustomjslink=true

or

&bypasscustomjslink=true

Then all the customized fields and views will be uncustomized until bypasscustomjslink=true is removed. While viewing and editing list items in this uncustomized mode, you can access and repair data as if you never had adjusted it with jslink.

Using this does not mean you can “relax” and start writing crappy code. You still have to produce good code and anticipate all possible errors. bypasscustomjslink is just a convenient “emergency exit” aimed for developers and support to quickly solve problems without needing to reset the JSLink property on fields and list views.

Advertisements

javascript: Remove illegal characters in url

Illegal characters

Recently I needed to create valid urls for pages using javascript. Also this time I thought it must be some out-of-the-box code for that in SharePoint. The first thing I came up  was the “Add page” dialog.  I found that the actual dialog was in the _layouts virtual folder:

/_layouts/15/CreatePublishingPageDialog.aspx

Bingo, it does the validation in the client side. This is the responsible javascript function that resides directly in the page:

function UpdateUrl() {
  LoadTermContextInfo();
  var hiddenPageUrlLabelExtensionClientId = "<%=hiddenPageUrlLabelExtension.ClientID%>";
  var hiddenPageUrlLabelExtension = document.getElementById(hiddenPageUrlLabelExtensionClientId);
  var pageNamePreviewUrlLabelClientId = "<%=pageNamePreviewUrlLabel.ClientID%>";
  var pageNamePreviewUrlLabel = document.getElementById(pageNamePreviewUrlLabelClientId);
  if( pageNamePreviewUrlLabel != null ) {
    var nameInputTextBoxClientId = "<%=nameInput.ClientID%>";
    var nameInputTextBox = document.getElementById(nameInputTextBoxClientId);
    var allowSpaces = false;
    if( GetInnerText(hiddenPageUrlLabelExtension) != "" ) {
      var suggestUrlValue = "";
      for (var i=0; i < nameInputTextBox.value.length; i++) {
         var currentChar = nameInputTextBox.value.charAt(i);
         if (IndexOfIllegalCharInUrlLeafName(currentChar) == -1 
			&& !(currentChar == ' ' && allowSpaces == false) 
			&& currentChar != '.' && currentChar != '+') {
           suggestUrlValue += currentChar;
         }
         else if (currentChar == ' ' 
			|| currentChar == '+' 
			|| (currentChar == '.' && i > 0 && i < (nameInputTextBox.value.length - 1))) {
          suggestUrlValue += '-';
        }
      }
      UpdatePreviewUrl( suggestUrlValue );
    } else {
      if( g_timerId != 0 ) {
        window.clearTimeout(g_timerId);
      }
      g_timerId = window.setTimeout(OnFriendlyUrlNameChanged, 500);
    }
  }
}

This function iterates through all the characters in the page url and removes the illegal characters. The space, plus sign and the dot become a hyphen. To determine if a character is illegal, it relies on another javascript function called: IndexOfIllegalCharInUrlLeafName. This function can be found in the init.js or init.debug.js:

function IndexOfIllegalCharInUrlLeafName(strLeafName) {
    for (var i = 0; i < strLeafName.length; i++) {
        var ch = strLeafName.charCodeAt(i);

        if (strLeafName.charAt(i) == '.' && (i == 0 || i == strLeafName.length - 1))
            return i;
        if (ch < 160 && (strLeafName.charAt(i) == '/' || !LegalUrlChars[ch]))
            return i;
    }
    return -1;
}

This function checks a char against an array of all characters: LegalUrlChars from the same file: init.js.

ill_002

To use this UpdateUrl function, we have to remove the references to the fields from the Add Page Dialog. Of course, we won’t overwrite this original function, we don’t want to break the SharePoint OOB functionality. Here is how my new function looks like:

var takana = {};
function takana.updateUrl(url) {
  var allowSpaces = false;
  if( url )
  {
    var suggestUrlValue = "";
    var length = url.length;
    for (var i=0; i < length; i++)     {
       var currentChar = url.charAt(i);
       if (IndexOfIllegalCharInUrlLeafName(currentChar) == -1
            && !(currentChar == ' ' && allowSpaces == false)
            && currentChar != '.' && currentChar != '+') {
         suggestUrlValue += currentChar;
       }
       else if (currentChar == ' '
            || currentChar == '+'
            || (currentChar == '.'
                     && i > 0
                   && i < (nameInputTextBox.value.length - 1))) {
         suggestUrlValue += '-';
      }
    }
  }
}

Server Side

For those of you who want run this operation on the server, here is the code written in C#:

//" # % & * : < > ? \ / { } ~ |
var illegalChars = @"[""#%&\*:\<\>\?\\\/\{\}~\|]";

pageName = Regex.Replace(pageName, illegalChars, string.Empty);

var punctuation = @"[\s\.;\+]";
pageName = Regex.Replace(pageName, punctuation, "-");

//remove "--"
pageName = Regex.Replace(pageName, @"\-{2,}", "-");

pageName = string.Format("{0}.aspx", pageName);

//do it like the built-in dialog, lower case
pageName = pageName.ToLower();

Don’t forget to leave a comment if you find this post useful.

Parameterize a javascript object and create url

If you want to add some parameters to an url which you want to open, you can use jQuery.param function:

var url = "some_url";
var params = { 
   name: "Setner",
   email: "setner@narspi.name",
   mobile: "123456789"
};
var search = "?" + $.param(p);
url += search;

It is handy, indeed. In an environment without jQuery (are there some?:) ) you can just iterate an object and join properties:

var url = "some_url";
var params = { 
   name: "Setner",
   email: "setner@narspi.name",
   mobile: "123456789"
};
if (url.match("/\?/g") == null) {
   url += "?";
}
else {
   url += "&";
}
var search = "";
for(var p in params) {
   search += [p, params[p]].join("=");
}
url += search;

This solution parameterizes an object and appends it to an url in a smart way (by adding a question mark or an ampersand depending on the situation).

SharePoint javascript API

There is a nice sharepoint javascript api we can use as well. Consider this example:

var u = new SP.Utilities.UrlBuilder("http://takana.com");
u.addKeyValueQueryString("id", "2");
u.addKeyValueQueryString("time", new Date().toISOString());
u.get_url();
//"http://takana.com?id=2&time=2012%2D02%2D24T12%3A30%3A53%2E339Z"
Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager - Coder, Speaker, Author

Office 365, SharePoint and Azure

SharePoint Dragons

Nikander & Margriet on SharePoint

Paul J. Swider - RealActivity

RealActivity is a specialized healthcare services and solution advisory firm.

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points !

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

Aryan Nava

| Blockchain | Serverless Architecture | Microservices Architecture | DevOps | AWS Lambda | Teraform |

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis