Reputation: 326
tell application "Safari"
set theVar to (do JavaScript "
var a =
document.getElementById('unitsdiv').getElementsByClassName('even');
var b = []
for (var i = 0; i < a.length; i++) {
b[i] = a[i].textContent;
};
console.log(b.length); \\ Returns 2
console.log(b[1]); \\ Returns item 2 of Array
console.log(b[0]); \\ Returns item 1 of Array
b; \\ Shows both items in Safari Console
") in document 1
end tell
log theVar -- Missing Value
The code works as expected in Safari Console. I have also tried initializing an list prior to running the do Javascript command with set theVar to {}
to no avail. Any help would be appreciated.
This seems to return one of the values
tell application "Safari"
tell document 1
set theVar to (do JavaScript "
var a = document.getElementById('unitsdiv').getElementsByClassName('even');
var b = [];
for (var i = 0; i < a.length; i++)
{ b[i] = a[i].textContent; };
console.log(b.length);
console.log(b[1]);
console.log(b[0]);
b[0];")
end tell
end tell
log theVar
If I try to take the array selector [0]
off of b
at the end of the javascript code then tell AppleScript to log theVar
it throws an error that that theVar
is not defined.
Upvotes: 0
Views: 630
Reputation: 326
The only solution I could come up with that isn't terrible, in case anyone else runs into this issue is
-- Function that allows you to pass a number from applescript to javascript to grab an item of an array.
on theFunc(theNum)
tell application "Safari"
tell document 1
set a to do JavaScript "var a =
document.getElementById('unitsdiv').getElementsByClassName('even');
var b = []
for (var i = 0; i < a.length; i++) {
b[i] = a[i].textContent;
};
b[" & theNum & "];"
end tell
end tell
-- returns item theNum of the Javascript array
return a
end theFunc
-- Initialize an array to contain the items returned from the loop below
set theArray to {}
-- Initialize a number to increment while the condition is true and pass to the function in the loop below
set theNum to 0
-- Use some string that is in each of items of the array, if you don\'t have a specific string, you could try to set it to something like \"does not contain \"missing value\" maybe, or length is something etc
repeat while theFunc(theNum) contains "LB"
set the end of theArray to theFunc(theNum)
set theNum to theNum + 1
end repeat
-- proof that the variable is an array and contains multiple items
repeat with a from 1 to the count of theArray
log item a of theArray
end repeat
Upvotes: 2