JavaScript functions to escape and unescape HTML

by timvasil 12/28/2008 9:10:00 PM

JavaScript doesn't have built-in functions to escape or unescape HTML, which may come in handy for certain DOM manipulations or AJAX scripting.  Here are the custom functions I wrote to handle these tasks.  I've tested the implementation with both IE and Firefox.

var g_oHtmlEncodeElement;

function htmlEscape(text)
{
    g_oHtmlEncodeElement = g_oHtmlEncodeElement || document.createElement("div");
    g_oHtmlEncodeElement.innerText = g_oHtmlEncodeElement.textContent = text;
    return g_oHtmlEncodeElement.innerHTML;
}

function htmlUnescape(html)
{
    g_oHtmlEncodeElement = g_oHtmlEncodeElement || document.createElement("div");
    g_oHtmlEncodeElement.textContent = g_oHtmlEncodeElement.innerText = "";
    g_oHtmlEncodeElement.innerHTML = html;
    return g_oHtmlEncodeElement.innerText || g_oHtmlEncodeElement.textContent;
}

Tags:

JavaScript | AJAX | IE | Firefox

Fix for IE's 'Operation Aborted' error

by timvasil 5/28/2008 11:17:00 PM

If you've done any dynamic manipulation of web pages, especially with AJAX or any other kind of web magic in the mix, you've run into IE's dreaded "Operation Aborted" error.

Here are some official comments on the issue:

The blog post says that if you aren't meeting all 3 conditions, you're OK.  In my case, I believe I wasn't meeting the 3 conditions, and yet the problem persisted.  It was very hard to reproduce, too.  I had to have the offending website in the "Internet Zone" and experience some network lag to make it happen.

In the end, I found that if I replaced this line:

   document.body.appendChild(element);

With this one:

   document.body.insertAdjacentElement('afterBegin', element);

Everything worked fine.  Of course, this trick works only if you're inserting a node whose position isn't important, e.g. it's a div you're going to give an absolute position anyway.

Along the way I had tried wrapping the appendChild calls in a try/catch block, but unfortunatley the append would work fine, and then IE would complain with "Operation Aborted" only after the JavaScript finished.  I was hoping for a global exception handler to trap the problem, but fortunately insertAdjacentElement fixes the issue!

Tags:

JavaScript | IE

Search

Calendar

«  June 2013  »
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

View posts in large calendar

Recent comments

Archive