A major complaint of ASP.NET WebForms is how the framework takes away control of the rendered document away from the developer - myriad components (both built-in to ASP.NET and third-party) are able to inject their own <script>
elements and other functionality into the rendered page.
My current issue is with the ClientScriptManager
(Page.ClientScript
).
A project I'm working on is a legacy WebForms project with hundreds of .aspx
that takes a massive dependency on a third-party web-controls and utility library which contains a copy of jQuery 1.4.1 as an embedded WebResource.
Whenever any control inside this library is used the controls register their private copy of jQuery through Page.ClientScript.RegisterClientScriptInclude
, like so:
class SomeControl : WebControl {
protected void OnInit() {
this.Page.ClientScript.RegisterClientScriptInclude(
this,
typeof(Page),
"jquery",
this.Page.ClientScript.GetWebResourceUrl( base.GetType(), "MyJQuery.1.4.1.js" )
);
}
}
This is a problem because the website needs to implement ASP.NET SignalR, which has a dependency on jQuery 1.6.4 or higher - but the library's controls are included literally thousands of times (including in the .master
files). I need to prevent this old jQuery library from being added to the page.
Subclassing all of the controls won't help because their code that calls RegisterClientScriptInclude
is buried in their Control.Init
or Control.Load
code with other essential functionality, and they often make a direct call to the static ScriptManager.RegisterClientScriptInclude
method, so subclassing Page
and overriding the ClientScript
property won't help either (it isn't a virtual
property anyway).
Other people have reported the same problem and asked the same question on StackOverflow, except they had the source-code of the libraries that inject the scripts - so they were simply instructed to change their code to not register the script in the first place - this is not an option for me - all I have is a multiple-megabyte-sized DLL I can only peek into using .NET disassembly tools.
- How to unregister Page.ClientScript in C# Asp.net
- Why can't you UnRegisterStartupScript?
- Removing scripts added by ClientScript.RegisterStartupScript
(In the third link, the solution doesn't work for me because I can't call RegisterClientScript
before the bad library does, and the first caller permanently sets the value, subsequent calls will not overwrite the script registration).
My hack-ish solution was to use .NET Reflection to overwrite the internal script registration - as ASP.NET WebForms is stable it means this is unlikely to break in the near future, but it's far from ideal. I'll post my solution as an answer - but if there are any solutions that don't use reflection I'll prefer those.