SharePoint and protocol-relative URL's

Introduction to protocol-relative URLs

Recently I learnt an amazing new trick, the protocol-relative URL where the scheme of a URL (the http bit) can be dropped and your browser will use the same scheme as the page’s URL. This is very useful when you have a website on both http & https. For example, you can set an image URL to be:

//demo.com/horse.png

If you browse to http://www.demo.com, then it will load the image from http://demo.com/horse.png, but if you go to https://www.demo.com, then it will load the image from https://demo.com/horse.png—and this works with CSS & JavaScript too!

This isn’t some odd browser trick; it’s in the standard for how URLs work.

To be clear, this is similar—but not the exact same as—absolute & relative URLs.

SharePoint

SharePoint (and, for this post, this has only been tested with 2010—your mileage may vary on newer or older versions) does not follow this standard and actually breaks protocol-relative URLs in two ways.

Front End

If you’re working on the SharePoint UI—putting content in a Content Editor Web Part or a text column in a list—and you edit the HTML and include a protocol-relative URL, SharePoint will "fix" it by inserting the current scheme. So no matter what you do, on the front end, you’re completely stuck.

Example

You put in:

<img src="//sharepoint/horse.png"/>

SharePoint will change it to:

<img src="http://sharepoint/horse.png"/>

(assuming your page is on an http scheme).

Back End

The other scenario is if you’re working with SharePoint web services—for example, the List Service—and setting HTML that way—SharePoint will once again "fix" things. Interestingly, it does something completely different from the front end. I guess the front end uses JavaScript, while the back end uses some other code. It removes the attribute entirely from the HTML.

Example

You put in:

<img src="//sharepoint/horse.png"/>

SharePoint will change it to:

<img/>

—yes, the src attribute is gone.