自动检测已打开的浏览器而不是打开默认浏览器

自动检测已打开的浏览器而不是打开默认浏览器

我的系统上有多个浏览器(Firefox、Google Chrome 和 Chromium)。
我通常根据需要一次使用其中一个,但是当其他应用程序想要打开浏览器时,它们总是打开其/系统默认浏览器。

是否有应用程序或脚本能够检测浏览器是否已在运行并将其用作当前的默认浏览器?

编辑

我不希望浏览器检测到它自己的实例!我想要一个浏览器请求程序/脚本来检测任何已打开的浏览器。

  • 例如,假设我有 Firefox、Google Chrome 和 Chromium,并且我单击 PDF 文件中的链接,并且 Chromium 已打开。我希望在 Chromium 中打开链接。
  • 另一次,Firefox 已打开。然后我希望在 Firefox 中打开该链接。

实际上,我希望已经打开的浏览器比系统默认的浏览器具有更高的优先级。

答案1

以下 Python 程序使用普苏蒂尔模块来获取属于您的进程列表,检查已知的浏览器是否正在运行,如果是,则再次启动该浏览器。如果找不到浏览器,则会启动默认浏览器。我添加了一些评论来澄清脚本中发生的事情。

除了脚本本身之外,您仍然需要使用以下命令使其可执行chmod并确保执行脚本而不是启动特定的浏览器。

#!/usr/bin/env python

import psutil
import os
import subprocess
import sys
import pwd

def getlogin():
    return pwd.getpwuid(os.geteuid()).pw_name

def start_browser(exe_path):
    # Popen should start the process in the background
    # We'll also append any command line arguments
    subprocess.Popen(exe_path + sys.argv[1:]) 

def main():
    # Get our own username, to see which processes are relevant
    me = getlogin()

    # Process names from the process list are linked to the executable
    # name needed to start the browser (it's possible that it's not the
    # same). The commands are specified as a list so that we can append
    # command line arguments in the Popen call.
    known_browsers = { 
        "chrome": [ "google-chrome-stable" ],
        "chromium": [ "chromium" ],
        "firefox": [ "firefox" ]
    }

    # If no current browser process is detected, the following command
    # will be executed (again specified as a list)
    default_exe = [ "firefox" ]
    started = False

    # Iterate over all processes
    for p in psutil.process_iter():
        try:
            info = p.as_dict(attrs = [ "username", "exe" ])
        except psutil.NoSuchProcess:
            pass
        else:
            # If we're the one running the process we can
            # get the name of the executable and compare it to
            # the 'known_browsers' dictionary
            if info["username"] == me and info["exe"]:
                print(info)
                exe_name = os.path.basename(info["exe"])
                if exe_name in known_browsers:
                    start_browser(known_browsers[exe_name])
                    started = True
                    break

    # If we didn't start any browser yet, start a default one
    if not started:
        start_browser(default_exe)

if __name__ == "__main__":
    main()

相关内容