Question

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"));
Was it helpful?

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

OTHER TIPS

Try adding a script tag and closer to the statement... usually works for me:

<script>
    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);
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top