1

This opens a new tab in Firefox browser:

from selenium import webdriver
browser = webdriver.Firefox()
browser.execute_script('''window.open("https://www.google.com/","_blank");''')

As a reference, here is the Selenium documentation:

**execute_script**(script, *args)
Synchronously Executes JavaScript in the current window/frame.
Args:
script: The JavaScript to execute.
*args: Any applicable arguments for your >JavaScript.
Usage:
driver.execute_script(‘return document.title;’)

I have a link in a String which I wish to open in a new tab using javascript (via execute_script).

Tried the following but it gives an error:

link = 'https://www.bing.com/'
java_script = '\'\'\'window.open(\"' + link + '\",\"_blank\");\'\'\''
browser.execute_script(script)

Error:

selenium.common.exceptions.JavascriptException: Message: SyntaxError: unexpected token: string literal
3
  • 1
    use r"string" or """string""" and just don't escape anything Commented Sep 5, 2020 at 18:06
  • and to handle variables, execute say "let x = 2; return 2;" and capture this in a python variable, it will work Commented Sep 5, 2020 at 18:06
  • Check out f string, there are well suited for the case where you want to put a variable in the middle of a string Commented Sep 5, 2020 at 18:16

1 Answer 1

1

F-string are well suited for that check them out

This will change your code to look like this:

from selenium import webdriver
browser = webdriver.Firefox()
link = 'https://www.bing.com/'
browser.execute_script(f"window.open('{link}','_blank');")
Sign up to request clarification or add additional context in comments.

2 Comments

If you add single quotation marks around the curly brackets like (f"window.open('{link}','_blank');") it works as wished. Thanks for helping!
Cool! I'll add it to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.