问题
I am trying to automate a search and a focusing on the part where the computer types in the search in the search bar. I think all of my syntax is correct but when I run the code, nothing happens and in the applescript result log it says "missing value"..
Here is my code:
to inputByID(theId, theValue) --defines the function--
tell application "Google Chrome"
open location "https://www.google.com "
execute javascript " document.getElementById(' " & theId & " ').value = ' " & theValue
end tell
end inputByID
inputByID("lst-ib", "hi ")
Is my syntax wrong or am I missing something? Any help appreciated..
回答1:
This works for me in macOS High Sierra:
to inputByID(theId, theValue)
tell application "Google Chrome"
open location "https://www.google.com"
repeat until (loading of active tab of front window is false)
delay 0.1
end repeat
tell active tab of front window
execute javascript "document.getElementById('" & theId & "').value = '" & theValue & "';"
end tell
end tell
end inputByID
inputByID("lst-ib", "Hello World!")
Aside from the fact that your execute javascript ...
line of code was a bit malformed, you can compare your's to mine for the difference, you also were not telling Google Chrome where the execute javascript ...
line of code was to be executed. Hence, e.g.: tell active tab of front window
Additionally, after using an open location ...
command, you also have to wait for the target of the execute javascript ...
line of code to exist, hence the use of the repeat until (loading of active tab of front window is false)
line of code after the open location ...
command, and before the execute javascript ...
line of code.
回答2:
" document.getElementById('" & theId & "').value = '" & theValue & "'"
Probably you got to remove the spaces before and after theId
so that it becomes ('myId')
instead of (' myId ')
and also add a quote at the end.
来源:https://stackoverflow.com/questions/51025760/result-missing-value-with-the-javascript-document-getelementbyid-method