Theme Switcher Demo

Table of Contents

A demonstration of controlling an embedded Anvil web application from its parent page.

Within the embedded app below, you can select a standard anvil colour scheme from the dropdown menu and you can toggle between its light and dark variants using the button. You’ll notice that the effect is applied to the embedded app only, not the parent page.

However, if you toggle the theme of this overall site, using the switch in the top right hand corner of this page, you’ll see that the change is also applied to the embedded app!

This is achieved by using the postMessage API to communicate between the parent page and the embedded app.

When the app starts, it first detects whether it is embedded within an iframe using a simple function:

import anvil.js


def within_iframe():
    return anvil.js.window != anvil.js.window.parent

If the app is within an iframe, it listens for messages from the parent page and assigns a handler for those messages. It then sends a message to the parent requesting the current theme:

if within_iframe():
    anvil.js.window.addeventlistener("message", self.on_message)
    anvil.js.window.parent.postmessage({"requesttheme": true}, "*")

In this example, the handler for any message received from the parent page is as follows:

def on_message(self, event):
    try:
        self.item = {"scheme": "Material", "variant": event.data.theme}
        switch_colour_scheme(**self.item)
    except Exception:
        return

You can see the full code for the embedded app at Github or, if you have an account with anvil, you can clone a copy for yourself.

Related Posts

PGP Signatures on Email

You’re probably here because you’ve received an email from me with an attachment called ‘signature.asc’ or with lines at the top similar to:

Read More

Taco Demo

We built a demonstration of Threshold Access Control (decentralised, conditional encryption) using the Anvil web application framework.

Read More

Everyone Pays to Attend PyCon UK

PyCon UK has a long-standing policy that everyone pays to attend - speakers, organisers, everyone. That often causes some consterntation with reactions like "I have to pay to speak at PyCon UK?!!" or "If I volunteer to help, I have to pay the same as someone who has done nothing?"

Read More