Missing Value Errors when heavily using Javascript in Safari by Applescript

前端 未结 1 1095
遇见更好的自我
遇见更好的自我 2020-12-20 05:51

Sorry for the possibly confusing title.

My problem is that I\'d like to download Apple\'s Command Line Tools for XCode without the need to click on the single button

相关标签:
1条回答
  • 2020-12-20 06:01

    As @Jordan stated above, the missing value returned from do JavaScript does not indicate an error. However, your code suffers from a few problems that do stop it from working:

    1. it does not wait for the page to load completely before trying to access the form – hence your value assignments and submit() call go into the void. You can go fancy and try to wait for a matching window name, but a simple delay will do;
    2. it tries to inspect the text content of all found elements (atags.textContent) instead of the currently looped-over one (atags[i].textContent);
    3. it tries to trigger a click event by calling the click() method, which most browsers refuse to do, ostensibly for security reasons (see this question and answer of mine). As Apple does not include jQuery, the issue is not quite as straightforward to sidestep as in the answer I linked to – you can, however, simulate the click event with a bit of code courtesy of Protolicious’ event.simulate.js.

    The following code will do what you asked for:

    tell application "Safari"
        set loadDelay to 2 -- in seconds; test for your system
        make new document at end of every document
        set URL of document 1 to "https://developer.apple.com/downloads/index.action"
        delay loadDelay
        do JavaScript "_connectForm = document.forms.appleConnectForm;
                       _connectForm.accountname.value = 'your_accountname';
                       _connectForm.accountpassword.value = 'your_accountpassword';
                       _connectForm.submit();" in document 1
        delay loadDelay
        do JavaScript "var _atags = document.querySelectorAll('a');
                       for (var i=0; i<_atags.length; i++){ 
                           if (_atags[i].innerText.indexOf('Command Line Tools for Xcode') === 0){ 
                               _event = document.createEvent('MouseEvents');
                               _event.initMouseEvent('click', true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, _atags[i]);
                               _atags[i].dispatchEvent(_event);
                               break;
                           }
                       }" in document 1
    end tell
    

    Tested with my own account; download of most recent Xcode Command Line Tools package (to be precise – topmost listed) started successfully.

    0 讨论(0)
提交回复
热议问题