Call_js() from a non-custom html form

I need to call a JS function defined in Native Libraries from various forms that are not custom html forms.

I have created a custom html form (called ‘js_gateway’) that contains a method to call the JS, and I import that into my other “normal” forms. I can then call the JS through the gateway form.

Is this the best/only way? Can anyone show me a better way?

There is a better way! (We’ve added it recently.)

You can run js.call_js in any Form to call a global JavaScript function. So if you have this in Native Libraries:

<script>
function addNumbers(a, b) {
  return a + b;
}  
</script>

You can have a Form like this:

from anvil import *

class Form1(Form1Template):

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run when the form opens.
    print(js.call_js('addNumbers', 20, 22))

And you’ll get 42 in the Output Panel when you run the app :smiley:

https://anvil.works/build#clone:APLTXBOTMXTUFI5H=SKXSMYLD4QERFLQMUO53FU2X

3 Likes

Thanks @shaun!

This is awesome! Now I have to resist the urge to refactor all those forms where I had a custom HTML component solely for the purpose of running Javascript. Going forward this is going to be much nicer.

4 Likes