Check if a Javascript function exists, if so call it.

I had a little trouble searching for this on Google. So here’s a little Javascript gem for you.

If you want to call a Javascript function, but only if it exists, here’s one way you can do that.

function ifFnExistsCallIt(fnName)
{
   fn = window[fnName];
   fnExists = typeof fn === 'function';
   if(fnExists)
      fn();
}

I use “fn” as a variable name inplace of the word “function,” since “function” is a reserved word in Javascript.

Two Javascript Tricks: click() and trim()

Man my poor blog hasn’t been updated in quite some time. What on earth could I do to remedy that situation? Wait, I GOT IT! I’ll add a new post! 🙂

Here are two really simple but really useful JavaScript tricks.

#1

document.getElementById(x).click();

The above is handy when you want to programmatically click a button for the user based on whatever logic you write. I used it to fire some ATLAS (now called ASP.Net AJAX) animations after I validated some fields.

#2

Add the following to your JavaScript library to trim the white space from the beginning and end of your strings.

String.prototype.trim=function()
{
	return this.replace(/^\s*|\s*$/g,'');
}

The above allows you to do this: xString = xString.trim();

Check out this Wikipedia article on ‘trim’. There are examples on how to trim a string for numerous programming languages.

http://en.wikipedia.org/wiki/Trim_(programming)

How to submit HTML without disabling ValidateRequest

So the scenario is this. You have an ASP.Net form field that you want the user to submit HTML to the server with. By default ASP.Net won’t allow this for security reasons. You could get around this by setting ValidateRequest=”false” in the page declaration or in the web.config. But, if you are developing a user control, you don’t want to make the developer using your control have to manage this. Another reason may be that subsequent developers may not be aware that you’ve deliberately opened up a security hole that has to be managed. So, you want to keep ValidateRequest enabled, but how?

To do this I wrote a little ‘encodeMyHtml’ JavaScript function that is called on the OnClick event when the HTML form’s submit button is clicked. The function encodes the user’s HTML input for the field I’ve specified into a harmless string before it is passed to the server. When I receive that input on the server I simply decode and go on my way.

ValidateRequest is happy, our users are happy, our peers are happy, heck we’re happy.

I add my ‘encodeMyHtml’ JavaScript function in my user control’s OnPageLoad method. This way I can make sure that my JavaScript is added to the parent page only once, no matter how many controls are on the page.

In my control’s OnPageLoad I call this:

private void addEditorJavaScript()
{
    // create our HTML encoder javascript function
    // this way it shows up once per page that the control is on
    string scr = @"<script type='text/javascript'>function encodeMyHtml(name){
                var content = document.getElementById(name).value
                content = content.replace(/</g,'<');
                content = content.replace(/>/g,'>');
                document.getElementById(name).value = content;
            }</script>";

    // add the javascript into the Page
    ClientScriptManager cm = Page.ClientScript;
    cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}

In my control’s ASPX I’m using a gridview. I wrap the gridview’s update asp:LinkButton in a span tag, and in that span tag I put my OnClickEvent.

<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
    <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span><span onclick="encodeMyHtml('  

When I get the input on the server side I simply call a couple of Replace methods on the input string to decode the HTML, and I’m done.