Question

I want to use AppleScript to paste some text into the current application while preserving the preexisting contents of the clipboard.

on writeFromClipboard(someText)
    set oldClipboard to the clipboard
    log oldClipboard
    set the clipboard to someText
    log (the clipboard)
    tell application "System Events"
        keystroke "v" using {command down}
    end tell
    log (the clipboard)
    set the clipboard to oldClipboard
end writeFromClipboard

writeFromClipboard("new text")

When I have old text on the clipboard when this script is run, I get the following event log and old text is pasted. I can only conclude that the text is actually pasted after the clipboard contents have been changed back.

tell application "AppleScript Editor"
    the clipboard
        --> "old text"
end tell
(*old text*)
tell application "AppleScript Editor"
    set the clipboard to "new text"
    the clipboard
        --> "new text"
end tell
(*new text*)
tell application "System Events"
    keystroke "v" using {command down}
end tell
tell application "AppleScript Editor"
    the clipboard
        --> "new text"
end tell
(*new text*)
tell application "AppleScript Editor"
    set the clipboard to "old text"
end tell

Short of adding a pause after the paste keystroke, is there a way to get this working?

Était-ce utile?

La solution

The Standard Additions Dictionary says:

set the clipboard to v : Place data on an application’s clipboard. Use inside a ‘tell’ block and activate the application first. (Link to AppleScript Wiki)

Try it this way:

on writeFromClipboard(someText)
    tell application "TextEdit"
        activate
        set oldClipboard to the clipboard
        set the clipboard to someText
        --delay 0.2
        tell application "System Events" to tell process "TextEdit"
            keystroke "v" using {command down}
        end tell
        set the clipboard to oldClipboard
    end tell
end writeFromClipboard

writeFromClipboard("new text")

For safety, I would still add a little delay.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top