Search code examples
pythonbrowsercgiurllib

How to detect the current open webbrowser and open new page in that same browser using Python?


I am making a website where I am using some html forms, which passes the values to a python script and in return the python script opens a new page/tab in the web browser. I am using the webbrowser module for it.

Although I can choose the default browser or any other browser using "webbrowser.get([name])"; but my concern is, as this will be a public webpage, so anyone can open the page in any browser of their choice.

The problem I am facing is : Lets say my default browser is "firefox", and I open the page in "chrome", so when the python script opens the new page it opens that in "firefox" instead of "chrome".


Here are my questions :

  • How do I detect the current web browser the user is using?
  • How to open the new page in that browser?

The code looks like this :

#!C:\Python27\python.exe -u
# -*- coding: UTF-8 -*-
import MySQLdb
import sys
import cgi
import re
import cgitb
import webbrowser

cgitb.enable()

print "Content-Type: text/plain;charset=utf-8"
print

try:
    db = MySQLdb.connect(host="localhost", user="root", passwd="", db="pymysql")
except MySQLdb.Error, e:
      print "Error %d: %s" % (e.args[0], e.args[1])
      sys.exit()

# ----- Do some analysis with the database ----
# ----- Create some kml files ----
# Use the kml files to display points in the map.
# Open the page where openlayers is present
webbrowser.open_new_tab('http://localhost/simulator.html')

Solution

  • The only reason that you are probably convinced that this is a working approach is most likely because you are running the server on your local machine. The python code you are executing is server-side so it has no control over the client. The client would normally be on a remote machine. In your case since your client is also on the server, you get the effect of seeing your python script open a browser tab with the webbrowser module.

    This is impossible in a standard client server web situation. The client will be remote and your server side code cannot control their machine. You may only serve back http requests which will simply be something their browser receives and renders. If you want to open tabs it will need to be a javascript solution on the client side.

    A more realistic solution would be to have your server serve back proper client side code. If the form is submitted via ajax then your response could contain javaacript that would open a new page.