How to create a new window and change its location (without CORS complaints)

I have an app that suggests the user what items to add to the cart and shows a list of links to our e-commerce site.

I would like to:

  1. When the user clicks on a link for the first time, have a new browser tab open to the specified URL. Then the user will decide whether to proceed with the add to cart button or not.
  2. The following clicks should recycle the already opened window and just change its location.

Here is the code I’m using:

class Summary(SummaryTemplate):
    def __init__(self, values, **properties):
        self.init_components(**properties)
        self.window_with_opencart = None
        [...]

    def click_on_row(self, **event_args):
        url = event_args['item']['url']
        if self.window_with_opencart and not self.window_with_opencart.closed:
            self.window_with_opencart.location.href = url
        else:
            self.window_with_opencart = anvil.js.window.open(url, '_blank')
        self.window_with_opencart.focus()

The first part works: the first time a link is clicked, it opens a new tab and navigates to the correct URL.

The second part doesn’t: when it tries to change the location of the existing tab, it says:
ExternalError: SecurityError: Failed to read a named property 'window' from 'Location': Blocked a frame with origin "https://wsaftr7itkm3o3tf.anvil.app" from accessing a cross-origin frame.

I thought that I wouldn’t be able to do anything with an already existing tab, but I would be able to manage a tab I have created, but I guess I was wrong.

I do have (partial) control of the OpenCart server, and I might be able to edit the CORS settings. But before going that route (which would require contacting an external contractor and starting experimenting semi-blindly, and every test would require a long back and forth of emails) I would like some expert opinion.

EDIT
I also would like to do something like this, but I’m getting similar CORS errors:

self.window_with_opencart.document.getElementById('quantity').value = '5';

you’ll need to send messages to and from the window and it’s opener

so you could fire off a message that says

hey can you reload please

and then the window can listen for that message and reload

That’s basically what anvil does when you run an app in a new tab
and then hit restart

you’ll want to look at the postMessage
and the addEventListener("message")


related post with some useful snippets

2 Likes

The good news is that I will not need to deal with CORS settings in the e-commerce site header.

The bad news is that I will need to add some Javascript to listen to the messages and execute the code to redirect to a new URL or to set some values.

I should be able to create an Anvil app and use that as test OpenCart site, to listen to my messages. When that works, I will add the code to the e-commerce site.