Injecting javascript from a module without a view

Topics: Customizing Orchard
Dec 14, 2012 at 12:13 AM

I have an Orchard module which when enabled I want to inject a java script into the head of every page. 

Is there a way to do this from the module without overriding one of the base views (like document.cshtml or layout.cshtml) in the module?

Is there a place in code that I could call Script.Include().AtHead(), like from a handler or something?

Dec 14, 2012 at 1:22 AM

I resolved this by implementing my own FilterProvider...

 

    public class MyCustomFilter : FilterProvider, IResultFilter
    {
        private readonly IResourceManager _resourceManager;

        public MyCustomFilter(IResourceManager resourceManager) {
                _resourceManager = resourceManager;
        }

        public void OnResultExecuting(ResultExecutingContext filterContext) {

            // Should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
                return;

            // Include the following script on all pages
            _resourceManager.Require("script", "My.Custom.Script").AtFoot();
        }

        public void OnResultExecuted(ResultExecutedContext filterContext) {
        }
    }

 

Then in my ResourceManifest.cs class in my module I just ensure I have defined the My.Custom.Script...

        public void BuildManifests(ResourceManifestBuilder builder)
        {
            var manifest = builder.Add();
            manifest.DefineScript("My.Custom.Script").SetUrl("my-custom-script.min.js").SetVersion("1.0").SetDependencies("jQuery");
        }