Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

Using JavaScript

This feature is optional - you do not need to know Javascript to use Anvil!

However, if you do know Javascript, and want to integrate with a low-level browser API or an existing Javascript library, this reference will allow you to access all those low-level details from Anvil.

Calling Javascript from Python

Every HTML Form (that is, any Form except a Blank Panel Form) has a call_js method that will invoke a Javascript function.

Here is a simple Javascript function that can be placed in an HTML template or a Custom HTML form.

<script>
function showJsAlert(message) {
  alert(message);
  return 42;
}
</script>

Here is the code to call that function from Python.

def button_1_click(self, **event_args):
  # This method is called when the button gets clicked
  self.call_js('showJsAlert', 'Hello, world!')

You can pass arguments to this function (any JSON-compatible value is supported: strings, numbers, lists, dicts and None). Likewise, you can return any JSON-compatible value from a Javascript function.

This is just an example. If you want to show a pop-up alert in your app, you should use Anvil’s alert() function instead!

You may also use the anvil.js.call_js() function to call global Javascript functions. This does not need to be called from an HTML form, it will work anywhere in client code. Unlike the call_js method described above, the Javascript this will not be bound when using the global anvil.js.call_js().

Referring to the form from Javascript

When you call a Javascript function from an Anvil form, this is bound to the (jQuery-wrapped) DOM node that represents the form itself (self). This means you have all the usual jQuery methods available to you, starting from the current component:

// (in Javascript:)
function setColor(color) {
  // Find all the 'div' elements inside this component
  var divs = this.find("div");
  divs.css("background-color", color)
}
This is just an example. If you want to change the background colour of something on your page, change the background property of a component instead!

Asynchronous Javascript

If you call a Javascript function from an Anvil form, and it returns a Promise, Python execution will block until that promise resolves (in which case, the resolved value is returned) or rejects (in which case, the reject value is thrown with an ExternalError exception).

// (in Javascript:)
function sleepForSomeTime(duration) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() { resolve(42); }, duration)
  })
}

Here’s the Python code that runs that Javascript:

# When the button is clicked, it will wait 5 seconds
# before printing '42' to the Output Panel:
def button_1_click(self, **event_args):
  r = self.call_js('sleepForSomeTime', 5000)
  print(r)

Running Javascript on Form startup

If you want to run Javascript on Form startup, run it from the show event handler.

  def form_show(self, **event_args):
    """This method is called when the HTML panel is shown on the screen"""
    self.call_js('initMyJavascriptLibrary')

This executes after the Form has been added to the page. Do not call_js() from your form’s __init__ method. A Form’s __init__ method runs before the Form is added to the page, and Javascript in the Form’s HTML template is not executed until it is added to the page.

Calling Python from Javascript

Any method on your Form can be called from Javascript. Imagine you have this method:

  def my_method(self, name):
    alert("Hello, %s!" % name)
    return 42

To call into Python from Javascript, call anvil.call().

The first argument is a DOM element (optionally jQuery-wrapped) that indicates which Form instance you would like to call the function on. It is not necessary to specify the exact DOM element of the Form; any child element will work. It is an error to pass a first argument that is not an Anvil HTML Form or a child of an HTML Form.

// (in Javascript:)
// Pop up a "Hello, World" Anvil alert when my-link
// is clicked.
$('.my-link').on('click', function(e) {
  var linkElement = this;
  anvil.call(linkElement, "my_method", "World").then(function (r) {
    console.log("The function returned:", r);
  });
  e.preventDefault();
});

The second argument is a method name, and all other arguments are passed to the Python method.

anvil.call() returns a Promise, which resolves to the method’s return value if it returns, or rejects with an exception object if it throws an exception. If the method throws an exception, the exception stack trace will be captured in the Anvil logs, regardless of the Javascript’s behaviour.

Javascript environment

Anvil pages execute within the Anvil runtime, which loads some Javascript components into the namespace. If your Javascript is acting weird, it might be because you have overwritten something important.

For example, it is a bad idea to load jQuery or Bootstrap Javascript explicitly from an HTML template — it will overwrite the versions Anvil has already loaded. Here is a partial list of Javascript libraries Anvil loads:

  • jQuery version 3 (minor versions may be upgraded without warning)
  • Bootstrap version 3.3
  • The Skulpt Python-to-Javascript compiler

Using Native JavaScript libraries

To use Native Libraries with Anvil, select the Native Libraries option in the App Browser.

Any HTML you add to the “Native Libraries” section will be inserted into the <head> tag of your Anvil app’s HTML. This is a great place to add a <script> tag to pull in an external library (or a .js file in your app’s Assets). You can also use <link> tags to refer to external CSS.

Importing JavaScript libraries. You can write &lt;meta&gt; tags in here too.

Importing JavaScript libraries. You can write <meta> tags in here too.