问题
I'm new to AppleScript and having trouble with this:
I'm creating a script for Chrome where I want to login to a site and check something for me. For now, I just need to check if I'm actually routed to the correct URL (sometimes I'm already logged in) or if I need to login (if the system has logged me out automatically). If I'm logged out, I just want to click the "Login" button (my credentials autofill). If I'm logged in already, then I'll just proceed with the rest of the script.
This is where I'm at:
activate application "Google Chrome"
tell application "Google Chrome"
open location "URL"
--Check if I have to login or not
--If I do, click the button "login"
--If not, proceed.
--The rest.
end tell
I was thinking of either: 1.) checking if I'm at the right URL and then if not, click the login button or 2.) check for presence of the login button and click it if it's present
I would love some direction on which way is more efficient and how to accomplish it. Struggling now to find the right commands... Thanks!
回答1:
Here is a script that opens the location, waits til it's done loading, checks the url for a particular string, and if it's there, presses a button using javascript.
tell application "Google Chrome"
activate
open location "http://somesite.com"
set theTab to tab 1 of window 1
repeat
if (loading of theTab) is false then exit repeat
end repeat
set theURL to URL of theTab
if theURL contains "login" then
execute theTab javascript "document.getElementById('login-button').click();"
end if
end tell
You'll need to change what string the script checks for in the url. You will also need to learn the button ID. Just browse the the source code (Menu View/Developer/) of the page to find that, and switch it out for 'login-button'. Look for a line like:
<button class="login submit" value="Login now" type="submit" id="login-button">
来源:https://stackoverflow.com/questions/24643251/how-to-check-if-im-at-the-right-url-in-applescript-chrome