AppleScript变量传递给JavaScript

时间:2012-08-07 13:56:26

标签: javascript applescript textedit

我将TextEdit中的文本存储在AppleScript变量中,我想将其传递给JavaScript。我以为我做得对,但我仍然无法获得存储的价值。代码如下:

tell application "TextEdit"
    activate
    set docText to the text of the front document --This works. I've checked.
end tell

tell application "Google Chrome"
    tell window 1
        tell active tab
            execute javascript "function encryptDocument() {
                plainText = '" & docText & "';
                return plainText;
                } encryptDocument();"
                set skurp to the result
                display dialog skurp
            end tell
    end tell
end tell

我在tell application "Google Chrome"命令中存放JavaScript代码的原因是因为每次尝试在之前的tell application "TextEdit"命令中调用它时都会出错。该错误始终表示它期望行尾,但找到"。不确定为什么,但我找不到解决这个问题的方法。

1 个答案:

答案 0 :(得分:3)

您想要赋予变量的值(我的意思是文本编辑器中的文本)是否包含单引号(')? 没有'在文本编辑器中,这似乎对我有用。

以下代码段可用于转义单引号。 (改编自this code

on escape(this_text)
    set AppleScript's text item delimiters to the "'"
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the "\\'"
    set this_text to the item_list as string
    set AppleScript's text item delimiters to ""
    return this_text
end escape

tell application "TextEdit"
    activate
    set docText to the text of the front document --This works. I've checked.
end tell

set docText to escape(docText)

tell application "Google Chrome"
    tell window 1
        tell active tab
            execute javascript "function encryptDocument() {
                plainText = '" & docText & "';
                return plainText;
                } encryptDocument();"
            set skurp to the result
            display dialog skurp
        end tell
    end tell
end tell