Last active
November 11, 2023 20:39
-
-
Save aaronk6/b6425c3ecef57ec7e6341618c139ce41 to your computer and use it in GitHub Desktop.
This script retrieves the URL and title of the active Safari tab, constructs an HTML link, and copies it to the clipboard. It also includes a plain-text representation in Markdown syntax.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
# Use osascript to get URL and Title from Safari | |
url=$(osascript -e 'tell application "Safari" to return URL of front document') | |
title=$(osascript -e 'tell application "Safari" to return name of front document') | |
# Strip Safari profile name | |
title=$(echo "$title" | sed 's/^[^—]*— //') | |
# Create HTML string with UTF-8 encoding | |
html=$(echo "<meta charset='utf-8'><a style=\"font-family: sans-serif\" href=\"${url}\">${title}</a>" \ | |
| hexdump -ve '1/1 "%.2x"') | |
# Create plain representation (Markdown syntax), escaped for usage in osascript below | |
plain=$(echo "[${title}](${url})" | sed 's/"/\\"/g') | |
# Use AppleScript to set the clipboard to HTML format and plain text. | |
# When omitting the plain text, some apps such as Slack will refuse to | |
# paste it - despite actually preferring the HTML version). | |
osascript <<EOF | |
set the clipboard to {«class HTML»:«data HTML${html}», string:"${plain}"} | |
EOF | |
# Return tab title for further processing (i.e. success message) | |
echo -n "$title" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment