Tasmotanizer
Tasmotanizer

Reputation: 377

Open URL in Python in existing tab

I'm using webcommands to control a Sonoff. To change the setting I run the following line in Python:

webbrowser.open('http://Sonoff_IP/cm?cmnd=POWER%20TOGGLE')

I am looking for a way to run the URL in the same tab, so as not to create a new tab every time the command runs.

Upvotes: 2

Views: 4729

Answers (2)

Davide Andrea
Davide Andrea

Reputation: 1413

Use Javascript:

OpenSameTab = '<script language="JavaScript" type="text/JavaScript">window.location = \'%s\';</script>'

and then

print OpenSameTab % 'file.py'

Upvotes: 0

DrewT
DrewT

Reputation: 5072

My understanding is that using if you are using webbrowser.open(<url>) it's not possible to avoid getting a new tab each time; with webbrowser it is possible to make sure it opens in the same browser window, but not in the same tab. To target the same window you need to set new=0 like:

webbrowser.open('http://Sonoff_IP/cm?cmnd=POWER%20TOGGLE', 0);

However, if you are able to open the link using the selenium library instead it is possible.

Read the docs for selenium and webdriver here: https://selenium-python.readthedocs.io/api.html

The main issue with doing it using Selenium is that, I think, you lose the ability to target the user's default web browser, and by default Selenium seems to default to Firefox since a lightweight port of Firefox is included in the Selenium library itself.

An example of opening a link in Selenium would be like:

from selenium import webdriver

link1="https://www.google.com"
link2="https://www.youtube.com/"
driver=webdriver.Firefox()
driver.get(link1)
driver.get(link2)

Selenium does support a lot of different browsers, so if you are able to get the user's default web browser from the webbrowser module or by some other method, you would be able to use that information to open URLs in the same tab with the user's default browser.

Hope this helps and good luck! :)

Upvotes: 2

Related Questions