Cheapskate applescript hack to get current selection from any frontmost application

Alec Jacobson

September 02, 2009

weblog/

So I wanted something as simple as tell current application to set selected_text to (selection as text). As far as I can tell this does not exist. So here's a cheap hack with obvious flaws:
tell application "System Events" to keystroke "c" using {command down}
delay 0.1 -- so copy can take place
set selected_text to (the clipboard as text)
-- replace the following with your script using the current selection
tell current application to display dialog selected_text
Note: If you don't have anything selected then selected_text gets set to whatever's in your clipboard. Worse than that, if you have selected some huge piece of text then delay 0.1 might not be long enough in which case again selected_text gets set to whatever's in your clipboard. That said, for now it is my only way to generalize my previously posted search selection on wikipedia script.