We can try. But first, some other code in your script:
Although that appears to work in simple cases, it's not reliable. Try this test: in the Finder, select, say, three files, and copy. You will see the the paste command on the Edit menu says Paste 3 Items. Now run this code:
Look at the Edit menu in the Finder: it now says Paste Item. You've lost two items, although you may not notice because their names are still in the string on the clipboard. The problems is that AppleScript's clipboard command wasn't updated when multiple clipboard items were introduced. Someone should log a bug, although I can't imagine it being a high priority.
So if you want to store the clipboard's contents and restore it reliably, you probably need to use something like this, which is adapted from some code on Stackoverflow:
use scripting additions
use framework "Foundation"
use framework "AppKit" -- for NSPasteboard
on fetchStorableClipboard()
set aMutableArray to current application's NSMutableArray's array() -- used to store contents
-- get the pasteboard and then its pasteboard items
set thePasteboard to current application's NSPasteboard's generalPasteboard()
set theItems to thePasteboard's pasteboardItems()
-- loop through pasteboard items
repeat with i from 1 to count of theItems
-- make a new pasteboard item to store existing item's stuff
set newPBItem to current application's NSPasteboardItem's alloc()'s init()
-- get the types of data stored on the pasteboard item
set theTypes to (item i of theItems)'s |types|()
-- for each type, get the corresponding data and store it all in the new pasteboard item
repeat with j from 1 to count of theTypes
set theData to ((item i of theItems)'s dataForType:(item j of theTypes))'s mutableCopy() -- mutableCopy makes deep copy
if theData is not missing value then
(newPBItem's setData:theData forType:(item j of theTypes))
end if
end repeat
-- add new pasteboard item to array
(aMutableArray's addObject:newPBItem)
end repeat
return aMutableArray
end fetchStorableClipboard
on restoreClipboard:theArray
-- get pasteboard
set thePasteboard to current application's NSPasteboard's generalPasteboard()
-- clear it, then write new contents
thePasteboard's clearContents()
thePasteboard's writeObjects:theArray
end restoreClipboard:
set theClip to my fetchStorableClipboard()
set the clipboard to "blah blah blah"
my restoreClipboard:theClip
I don't know if that will solve your problem, though -- it sounds to me awfully like a timing issue. You could try adding a delay after the "set frontmost to true".