Leverage Javascript inside sharepoint web parts

Home | SharePoint Development | Leverage Javascript inside sharepoint web parts

Many a times, we’d find the need for leveraging the javascript in sharepoint web parts. It could be a simple requirement of opening up a pop-up window or could be  a complex requirement to invoke a web service from javascript. Here is code-snippet and steps to leverage java script inside sharepoint web parts. The crux is to embeed or register the javascript function in the PreRender event of the web part and invoke this registered javascript, from wherever desired.

//In the constructor of the web part, define a delegate of the PreRender method.
    public SampleWebPart()
        {
            this.PreRender += new EventHandler(SampleWebPart_ClientScript_PreRender);

        }

        #region register javascript methods

//In the delegate method of PreRender, call the another method that does the registering of javascript
        // Client script registration event
        private void SampleWebPart_ClientScript_PreRender(object sender, System.EventArgs e)
        {
            RegisterJavaScript();
        }
//Use the RegisterClientScriptBlock method of the Page object, to register the javascript
        //Function will embedded script
        protected void RegisterJavasScript()
        {

            //format the string to hold the javascript
            string embeedscript = "   <script>" +
                                    "function openNewWin(url) {" +
                                        //"var x = window.open(url, 'mynewwin', 'width=1200,height=800');" +
                                        "var x = window.open(url);" +
                                        "x.focus();" +
                                            "} " +
                                   "</script>";

            string OpenScriptKey = "OpenNewWin";
            //check whether the javascript has been already registered to the page
            if (!Page.IsClientScriptBlockRegistered(OpenScriptKey))
            {
                Page.RegisterClientScriptBlock(OpenScriptKey, embeedscript);

            }

        }

protected void Button1_click(object sender, ImageClickEventArgs e)

        {

//invoke the javascript function that opens the application page  in new window
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>openNewWin('" + url + "')</script>");                

}

 Subscribe to my post

Leave a Reply