Search code examples
c#asp.netdotnetnukehttpmoduleihttpmodule

Add javascript into httpmodule of DNN


I have httpmodule in DotNetNuke. How to add a javascript file to this httpmodule?

I tried this, but it didn't work:

string text = "<script type=\"text/javascript\">";
text = ((text + "$(document).ready(function () { alert('worked');" + "if ($('div').hasClass('classa')) {") + string.Format("$(\"#Body\").append(\"<script src='{0}' type='text/javascript'><\\/script>\");", "~/Resources/Rasta/JS/" + "myjs.js") + "}") + "});" + "</script>";

 page.RegisterClientScriptBlock("mykey" + Guid.NewGuid().ToString(), text);

and use this code( that worked in another module) but it didn't work too:

ClientResourceManager.RegisterScript(page, page.ResolveUrl("~/Resources/myjss/JS/myjs.js"));

Solution

  • Try this code in your IHttpModule

    public void Init(HttpApplication context)
    {
        context.PreRequestHandlerExecute += new EventHandler(this.RegisterPagePrerenderHandler);
    }
    
    private void RegisterPagePrerenderHandler(object s, EventArgs e)
    {
        if (HttpContext.Current.Handler is Page)
        {
            Page page = (Page) HttpContext.Current.Handler;
            page.PreRender += delegate (object ss, EventArgs ee) {
                if (page is CDefault)
                {
                    page.ClientScript.RegisterClientScriptInclude("key", page.ResolveUrl("~/myjs.js"));
                }
            };
        }
    }
    

    thanks to Morteza