代码之家  ›  专栏  ›  技术社区  ›  Disco Globeulon

传递给JavaScript的AppleScript变量

  •  0
  • Disco Globeulon  · 技术社区  · 13 年前

    我将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
    

    我把JavaScript代码放在 tell application "Google Chrome" 命令是因为每次尝试在前一个命令中调用它时都会出现错误 tell application "TextEdit" 命令错误总是说它期望一条线结束,但却发现 " 。不太清楚为什么,但我找不到解决这个问题的方法。

    1 回复  |  直到 13 年前
        1
  •  3
  •   Vortexfive    13 年前

    你想给变量的值(我指的是文本编辑器中的文本)是否可能包含一个引号(')? 在文本编辑器中没有“”,这似乎对我有效。

    以下代码片段可用于转义单引号。(改编自 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