Firefox Link Paster script

Hi–

I’m trying to write a script that will make it easy to insert links into text boxes when I’m writing comments on blogs. For example, I might want to say:

This link is cool.

My algorithm for this:
– manually copy the URL to the clipboard
– type “This link is cool.” into the text box
– select the text “This link”
– run the following script:


-- Assuming the URL is in the clipboard...
-- This part will prepare the link parts for pasting
set preText to "<a href=\""
set postText to "</a>"
set theLink to «class ktxt» of ((the clipboard as text) as record)

-- Now that the URL is saved in theLink, go to Firefox and replace the clipboard with the selected text ("This link" in the example)...
tell application "Firefox" to activate
tell application "System Events" to keystroke "c" using {command down}
set linkWords to "\">" & (the clipboard as text)

-- Now that the text to replace is saved in linkWords and the text is still selected in the text box, set the clipboard to the fully-constructed link, with tags, and paste to replace the text in the text box
set the clipboard to preText & theLink & linkWords & postText
--display dialog "About to paste: " & (the clipboard as text)
tell application "Firefox" to activate
tell application "System Events" to keystroke "v" using {command down}

The problem is that it works very inconsistently. Sometimes it’s perfect. Other times it just doesn’t paste anything. Uncommenting the “display dialog” in the last block reveals that often, the URL is saved in the variable linkWords, meaning that the selected text box text wasn’t copied to the clipboard correctly.

Is there a better way to do this? Could it have to do with having multiple tabs in the window in Firefox?