Close the Anvil app window or use one tab to programmatically open two different Anvil apps (one app embedded in another)

What I’m trying to do:
I’m trying to close my Anvil app window programmatically. Alternatively, I want to open both Apps (one app embedded in another) in one tab and navigate back from the second app to the first app programmatically.;

What I’ve tried and what’s not working:
I’ve tried to add the window.close() function in the event handler function, but it did not work. However, when I tried the function in a JavaScript file, it worked fine. This approach will be helpful and effective in a case where the second app is used, allowing us to programmatically revert to app one without having to do it manually, which could be ineffective for the intended usage purpose.

Client Code:

from ._anvil_designer import Form1Template
from anvil import *
import anvil.js
import time
from anvil.js.window import localStorage
from anvil.js import window
import anvil.users
import anvil.server

class Form1(Form1Template):

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


  def close_anvil_window(self, **event_args):
    window.close()

When I run your code in a new tab, it works fine. When I run your code embedded in the IDE, it doesn’t work, because the IDE uses an iframe to show the running app. So to test your code, just run it in a new tab:

image

1 Like

Wow, thank you! That worked perfectly well. Now, how will I be able to execute it using the publish link instead of debugging, so that it closes the window? I tried using the link, but it fails to close. Is there a code or configuration I need to apply and how?

Huh, looks like you’re running up against a security feature of Javascript. Apparently the browser doesn’t think that the window was opened by your script (since the user typed in the URL), and so your script cannot close it. Your script can only close windows that were opened by it (so if you used window.open to open a new tab, your script could close it).

Do some Google searching on something like “Javascript close own window” to see some of the discussions on the topic.

Alas So, does that mean I will have to provide the JavaScript code in the Anvil Native library and call it from the client-side code via the server module? If you don’t mind, could you please show me how to run the JavaScript on Anvil in case I find the solution on Google?

No, it has nothing to do with where the Javascript is run. Your previous code was using Javascript (through the Anvil Python bridge).

If you find a way to use Javascript to close a user opened tab, then that Javascript can be converted to run from Python in Anvil, using the anvil.js bridge.

Thank you so much for giving me a breakthrough. This code solved my concern: window.setTimeout(window.close, 10000); .

1 Like