AppleScript variables passed to JavaScript

一笑奈何 提交于 2019-12-06 15:24:22

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/11847594/applescript-variables-passed-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!