如何从 Firefox 当前选项卡获取 url,而不需要安装额外的软件?

Alf*_*.37 5 bash url firefox wmctrl

可以使用 xdotool 获取当前选项卡:

# set focus to address on browser
xdotool search --onlyvisible --classname Navigator windowactivate --sync key F6

# copy address from browser tab to clipboard
xdotool search --onlyvisible --classname Navigator windowactivate --sync key Ctrl+c

# get off the focus from address from browser tab
xdotool search --onlyvisible --classname Navigator windowactivate --sync key F6

# delivery of clipboard content to variable
clipboard=`xclip -o -selection clipboard`

# clear clipboard
xsel -bc; xsel -c

# echo URL of active tab of active browser
echo $clipboard
Run Code Online (Sandbox Code Playgroud)

由于 xdotool 存在缺陷,有时会在不停止上述代码的情况下触发按键,因此我需要另一种方法来执行相同的操作,也许使用 wmctrl。

这是我在 bash 上使用 wmctrl 尝试过的;它对我不起作用:

id=$(wmctrl -l | grep -oP "(?<=)(0x\w+)(?=.*Firefox)")

# set focus to address on browser
xdotool key --window $id "ctrl+l"

# copy address from browser tab
xdotool key --window $id "ctrl+c"

# delivery of clipboard content to variable
url=`xclip -o -selection clipboard`

# clear clipboard
xsel -bc; xsel -c

# echo URL of active tab of active browser
echo $url
Run Code Online (Sandbox Code Playgroud)

Ark*_*zyk 5

我不会为此使用 xdotool - 它太脆弱且容易出错。请使用适当的浏览器自动化工具,例如 Marionette。安装 marionatte_driver python 模块:

pip3 install --user marionette_driver
Run Code Online (Sandbox Code Playgroud)

使用 --marionette 选项启动一个新实例 firefox:

firefox --marionette
Run Code Online (Sandbox Code Playgroud)

使用以下 get_url.py:

#!/usr/bin/env python3

import marionette_driver

m = marionette_driver.marionette.Marionette()

m.start_session()
print(m.get_url())
m.delete_session()
Run Code Online (Sandbox Code Playgroud)

例子:

$ ./get_url.py
https://unix.stackexchange.com/questions/629440/how-to-get-the-url-from-current-tab-of-firefox-by-help-of-wmctrl
Run Code Online (Sandbox Code Playgroud)

您可以./get_url.py使用命令替换将 的输出保存到变量:

$ url="$(./get_url.py )"
$ echo $url
https://unix.stackexchange.com/questions/629440/how-to-get-the-url-from-current-tab-of-firefox-by-help-of-wmctrl/629447?noredirect=1#comment1177925_629447
Run Code Online (Sandbox Code Playgroud)