如何在Automator中使用AppleScript实现Safari页面选中文本与当前URL拼接并生成带文本定位锚点的剪贴板链接
Solution for Creating a Safari Text Selection Deep Link Quick Service
Hey there! Let's fix this up for you step by step—you're already halfway there with your existing code, we just need to fill in the missing pieces for grabbing selected text and handling URL encoding.
Step 1: Complete AppleScript Code
Replace your partial code with this full script, which handles all your requirements:
tell application "Safari" -- Grab the current tab's URL (your original working code!) set theURL to URL of current tab of window 1 -- Fetch the selected text from Safari using JavaScript (since AppleScript can't access page selections directly) set selectedText to do JavaScript "window.getSelection().toString();" in current tab of window 1 -- Exit early if no text is selected to avoid errors if selectedText is "" then display alert "Oops!" message "Please select some text in Safari first before running this service." return end if -- URL-encode the selected text (handles spaces, special characters, etc.) set encodedText to do JavaScript "encodeURIComponent('" & selectedText & "');" in current tab of window 1 -- Build the final deep link with the required anchor set finalLink to theURL & "#:~:text=" & encodedText -- Copy the finished link to your system clipboard set the clipboard to finalLink end tell
Key Fixes for Your Original Issues:
- Getting selected text: AppleScript doesn't have a native way to pull selected text from Safari's webpage content, so we use a small JavaScript snippet (
window.getSelection().toString()) to fetch it. - URL encoding: Instead of manually replacing spaces, we use JavaScript's
encodeURIComponent()function—it safely encodes all characters that need special handling (not just spaces, but quotes, symbols, etc.). - Error handling: Added a check for empty selections to prevent the service from running without valid input.
Step 2: Set Up the Automator Quick Service
Now let's wrap this into a usable Quick Service:
- Open Automator and choose Quick Service as your document type.
- In the left-hand action library, search for Run AppleScript and drag it into the right-hand workflow area.
- Delete the default AppleScript code and paste the full script above.
- Configure the top workflow settings:
- Set Service receives selected to
no input(we're pulling text directly from Safari, not relying on Automator's input). - Set in to
Safariso the service only appears when you're using Safari.
- Set Service receives selected to
- Save the service with a name like "Copy Selection Deep Link".
Step 3: Test It Out
- Open Safari, navigate to any page, and select some text.
- Go to the Safari menu → Services → select your new service.
- Paste from your clipboard—you'll get the formatted deep link exactly like your example!
内容的提问来源于stack exchange,提问作者spooky
相关产品推荐
相关产品推荐

