Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, December 05, 2011

Encoding html using JavaScript escape and unescape


There are a couple of reasons that you may want to encode some (or all) of your source html, these include:
  • Slightly increased security - by protecting your source from being easily read you are making it more difficult for anyone trying to find a workaround to your site (includes spoofing payments and gaining access to members areas)
  • Protection for automated non-javascript enabled crawlers - many of these are used to harvest email addresses from websites to add to spam mailing lists, and encoded email address will not be recognised as they cannot process the javascript.
There is also a downside however. Users of your website may well be veiwing it on a non-javascript enabled browser or have javascript turned off (usually done to avoid malicious scripts and auto-popups), if the site user is unable to process the javascript then they too will be unable to read the information that has been encoded and it will appear missing from the page.


Top of Form
Enter the text to encode here:
 


Encoded html:
 <script type="text/javascript">document.write(unescape("

"));</script>

Bottom of Form
How it's done
It's encoded by using the escape() function and then further special characters are encoded using the following routine:
   function encodeMyHtml() {
     encodedHtml = escape(encodeHtml.htmlToEncode.value);
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
     encodeHtml.htmlEncoded.value = encodedHtml;
   }
It is then dispayed by utilising the unescape() fuction which will turn it all back into html:
<script type="text/javascript">document.write(unescape(" my encoded html "));</script>

No comments:

Post a Comment