Apple Event: May 7th at 7 am PT

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Can I write a script that copies selected text from Safari into Textedit?

I'm trying to create a script that copies the selected text from Safari and also copies the URL of the current page and pastes both of them into a new Textedit document.

I I can get all the text of the web page into the Textedit document, but I don't know how to get just the selected text. What is the syntax?

MacBook 1,1, Mac OS X (10.5.7)

Posted on Jun 17, 2009 1:30 PM

Reply
Question marked as Best reply

Posted on Jun 17, 2009 3:59 PM

Use the "do javascript" command:

tell application "Safari"
set HisWords to do JavaScript "window.getSelection()" in current tab of front window
end tell



User uploaded fileAK
6 replies

Jun 17, 2009 4:06 PM in response to GeorgeXIII

The following script will do exactly what you want.

tell application "Safari"
activate
tell application "System Events"
keystroke "c" using command down
set theText to the clipboard
keystroke "lc" using command down
set theText to theText & return & return & (the clipboard)
end tell
end tell
tell application "TextEdit"
activate
make new document with properties {text:theText}
end tell

Jun 17, 2009 5:39 PM in response to Pierre L.

The preceding script was doing the job, but the following one is still better, since it doesn't affect the selection in Safari:

tell application "Safari"
activate
set theURL to URL of front document
tell application "System Events"
keystroke "c" using command down
end tell
end tell
set theText to (the clipboard) & return & return & theURL
tell application "TextEdit"
activate
make new document with properties {text:theText}
end tell

Jun 18, 2009 6:03 AM in response to GeorgeXIII

Thanks, guys.

I think the javascript solution works better than the system events solution.
I notice with the system events approach, if I select a picture with the text I get an error -25131.

The javascript solution gives me the text, ignoring any pictures I might have selected. This is fine, I don't want to have pictures in my document, but it can be hard on some sites to select the text one wants without selecting a picture.

Can I write a script that copies selected text from Safari into Textedit?

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.