简体   繁体   中英

AppleScript variables passed to JavaScript

I am storing text from TextEdit in an AppleScript variable, and I want to pass it to JavaScript. I thought I was doing it right, but I still can't get the value to be stored. The code is as follows:

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

The reason I house the JavaScript code within a tell application "Google Chrome" command is because I get an error every time I try to call it in the previous tell application "TextEdit" command. The error always says that it expects an end of line but found " . Not really sure why, but I can't find a way around this problem.

Is it possible that the value you want to give to the variable (I mean the text in Text Editor) contains a single quote (')? Without ' in Text Editor this seems to work for me.

The following code snippet may be used to escape single quotes. (adapted from 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM