How to use JS in Plone addon

I'm working on plone.importexport and need help with registring JS in the add-on.
I followed this. But it seems a bit confusing and unsuccessful.
This is what I have tried so far.

Can you access the file from http://localhost:8080/Plone/++resource++plone.importexport/script.js ?

Also, do not name the resource as browser, which is way too generic and may conflict with other resources. I'd suggest changing the prefix from plone.resources/browser to plone.resources/importexport-myscript instead. Use a more specific name for myscript depending on what it does, e.g. plone.resources/importexport-controlpanel or plone.resources/importexport-widget.

Last step you must register the resource into an enabled bundle or include it in a view by view basis with add_resource_on_request as the training suggests.

Is there a more genric way to add this in configure.zcml rather then adding in view.py?

Though I'm able to access my js script but I'm not able to play with it in the adddon, which means there is still some path error.
These are the changes I made. One may look into it to suggest the correct solution.

You have to pass the resource name to add_resource_on_request, which is not 'plone.importexport', but the name you gave to it in registry.xml. As per my suggestions above, importexport-controlpanel or importexport-widget (or exercise1, as per the documentation link you posted).

If you want your JS to be loaded globally, instead of specific views, you need an additional entry in registry.xml in order to register a bundle, see: https://docs.plone.org/adapt-and-extend/theming/resourceregistry.html#bundle-example-records

@Shriyanshagro You don't really need to register your resources using the resource registry, unless you expect this to be something used across the whole site, or a large portion of it.

As I understand, this is a Javascript that is only used here, so just add a good old <script type="text/javascript" src="//++resource++plone.importexport/script.js"></script> in your <head> section and that should be it.

I agree with @davilima6 that you should name your script with a more descriptive name, something like "import_export.js" sounds ok to me...

What do you mean by this? Please elaborate

Sorry, it got filtered out, just a normal script tag inside the head

I suspect you want to put the script tag referencing the js resource in the javascript_head_slot in the template(s) you need this JS in.

1 Like