I know I can use keyboard maestro to run JavaScript in Safari tab. however, I tried to do it from a python script. And I am failing. I think the script is failing because osascript arguments are not escaped.
Hope this is ok to ask here as it is not Keyboard Maestro question but is a Python / JXA / JS question.
My python code which runs when the desired page is open in Safari. In this case the desired page for example is https://www.w3schools.com/html/html_tables.asp
import subprocess
def run_jxa(jxa_script, data:list):
args = ["osascript", "-l", "JavaScript", jxa_script]
for x in data:
args.append(x)
output = subprocess.run(args, capture_output=True)
return output
def main():
script_file = "get_safari_element_jxa.js"
with open(script_file, 'r') as f:
jxa_script = f.read()
js_for_safari_file = "get_safari_element.js"
with open(js_for_safari_file, 'r') as f:
js_for_safari = f.read()
output = run_jxa(jxa_script, [js_for_safari])
print(output)
if __name__ == "__main__":
main()
File get_safari_element_jxa.js contains:
function run(argv) {
'use strict';
var safari = Application("Safari");
var safari_script = argv[0];
var output = safari.doJavaScript(safari_script, {
in: safari.windows[0].currentTab
})
return output;
}
File get_safari_element.js contains:
function get_data(xpath){
var elements = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var element = elements.snapshotItem(0)
return element.innerHTML;
}
xpath = '//*[@id="customers"]';
get_data(xpath);
If somebody can review the above code and advise how I can get the desired result, I would be grateful.
My primary script is in python because I know that the best. I do want to use doJavaScript function as that allows me to have full control over the open Safari page.
Thank you for reviewing the question and for your help.