可以使用 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
由于 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
答案1
我不会为此使用 xdotool - 它太脆弱且容易出错。使用适当的浏览器自动化工具,例如 木偶。安装 marionatte_driver python 模块:
pip3 install --user marionette_driver
使用 --marionette 选项启动一个新实例 firefox:
firefox --marionette
使用以下 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()
例子:
$ ./get_url.py
https://unix.stackexchange.com/questions/629440/how-to-get-the-url-from-current-tab-of-firefox-by-help-of-wmctrl
您可以./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
答案2
这是另一种写法
# Search for the visible Firefox window(s) and get its window ID
window_id=$(xdotool search --onlyvisible --class "firefox")
# Send the keyboard shortcut to open the URL bar, copy the URL to clipboard and then close the URL bar by sending the Escape key.
# The command is sent to the Firefox window with the specified ID using the --window option.
xdotool key --window $window_id --delay 20 --clearmodifiers ctrl+l ctrl+c Escape
# 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
答案3
您可以修复示例代码中与 xdotool 相关的问题。请参阅以下示例代码来修复 xdotool 错误:
#!/bin/bash
while true; do
echo Get current_wid
current_wid=$(xdotool getwindowfocus) # Get wid of current window and save this value for go bac later
echo "$current_wid"
echo
echo
echo F5 senden
xdotool windowactivate --sync "$current_wid" key --clearmodifiers F5
echo
echo
echo Fix von aktivem Fenster
xdotool windowactivate "$current_wid" # Done, now go back to where we were
echo
echo
echo "sleep 1"
sleep 1
done
echo "Zum Beenden Enter drücken oder Ctl + C."; read -r