How static resources are resolved within a module

Hi all

I am creating a module and I want to use js and css files inside my jsp files. I noticed that in some modules when they have jsp views inside the webapp folder like hello.jsp. Inside controllers the view is resolved as “/module/moduleId/hello” where openmrs will definitely add the .jsp at the end.

Now I have the following files webapp/hello.jsp and webapp/resources/hello.js. I tried using <script src="…/resources/hello.js"/> inside the jsp file to include the hello.js but I get 404

Use something like this:

@dkayiwa thanks. Please help me understand how this is resolved file="/moduleResources/xforms/formdesigner/FormDesigner.nocache.js. I mean if I have .js file inside moduleName/omod/src/main/webapp/js/hello.js how would I my html include code look like?

Put it under resources in a path like …/webapp/resources/js/hello.js

Then you would use:

<openmrs:htmlInclude file="/moduleResources/moduleName/js/hello.js"/>
1 Like

@dkayiwa the above was indeed helpful. I was able include javascript files into my jsp page using that.

Now can’t seem to figure this one out;

I have a jsp file in webapp/views/hello.jsp

and a javascript file in webapp/resources/js/sw.js

I want to register a Service Worker from the hello.jsp page. I have placed this code inside the hello.jsp

    if ("serviceWorker" in navigator) {
        console.log("Service Worker Available!!!");
        navigator.serviceWorker.register("../resources/js/sw.js").then(function(registration) {
        }).catch(function(error) {
            console.log("error!", error);

When I deploy and test the application, I get this output. Looks like the sw.js file is not been found

Service Worker Available!!! helloWorldForm.form:1484 error! TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

Did you try this? navigator.serviceWorker.register("<openmrs:htmlInclude file='/moduleResources/moduleName/js/sw.js'/>").then(function(registration) {

I just realised the above would not work because it just creates a script tag. Did you try this? navigator.serviceWorker.register("../moduleResources/moduleName/js/sw.js").then(function(registration) {

@dkayiwa thanks. But that didn’t work either. This is a huge blocker for us. Do you think platform will need some enhancements to have this working?

@jtabot, see e.g. how you can construct js url…

1 Like

@raff thanks. That worked like a charm :slight_smile:

@raff can I use that in an external javascript to resolve resources or is it only allowed in jsp pages?

say I have an external javascript that is included in my jsp page and inside my javascipt i want to resolve file paths in strings like ‘/css/main.css’

js files are not processed by the container…

The typical approach is to define a js global variable CONTEXT_PATH = ${pageContext.request.contextPath} in a jsp page and then use it in your scripts.