How to make a link open in the current tab

I’m trying to make my link open in the current tab but I can’t figure out how. I just started working on Anvil so I’m still working on the basics. Please answer ASAP.

1 Like

Is the link for an external webpage or still within your anvil app?

could you give a little more - a code snippet perhaps? What you’ve tried and what doesn’t work.

1 Like

it’s not on the anvil website

Hi @choprasahil.sc, do you mean the link opens an external url like google.com? Or a link opens an url of your anvil app

1 Like

My link is sent to google.com. So isn’t that a redirect? If so how do you do them?

So how do i do them?

a bit late but you can do something like:

in Native Libraries:

function open_url_same_tab(url) {
  window.open(url, "_self");
}

link click event

self.link.tag = some_url # set this in the design view

def link_click(self, **event_args):
  js.call_js('open_url_same_tab', self.link.tag)

proof of concept
https://anvil.works/build#clone:FPDIXYWNGETIDKY4=RTZT5HHDHUEY6QJN2K5HGRAP



EDIT: since this post anvil has improved its js integration:

from anvil.js import window

def link_click(self, **event_args):
  window.location = url
  # or window.open(url, "_self")

If you want to open it in a new tab you could use window.open(url) instead

7 Likes

Thank you for the script it works!

1 Like

I think the answer here is a better one

anvil.js.window.location = url
2 Likes

Good spot @sysadmin and welcome to the forum - I’ve edited the post above so that others looking in the forum can see the better answer.

In September 2020 - the anvil.js module didn’t exist :wink:

2 Likes

If I replace the internal link “https://anvil.works/…” of this app with 'https://google.com" it will produce an error

Refused to display 'https://www.google.com/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Is there an alternative nowadays (in the year 2022)?

This code is working for me:

window.location = url #for same window
anvil.js.window.open(url, ‘_blank’) #for different tab

I know this is primarily about opening in the same tab, but:

The ‘different tab’ option was working on Desktop (Safari) but didn’t work on my iPhone (also Safari). If you want to open things in a different tab on mobile, probably best to stick with Links components.