AppleScript URL from open safari window

applescriptsafari

I have a Safari window displaying a webpage. I want to be able to retrieve the open URL into AppleScript. However when I do this:

if URL of window 1 is "www.google.com" then
    --do something
end if

It returns an error of nothing being returned. And I'm pretty sure window 1 exists because in another part of the program I created the window.

Can someone tell me the mistake I made?

Best Answer

URL is a property of a document or a property of a tab in a window, so use this:

if URL of document 1 is "www.google.com" then

or this:

if URL of current tab of window 1 is "www.google.com" then

Update, example of how to use the exists command:

tell application "Safari"
    set b to exists URL of document 1 -- this put false or true into the variable
    if b and URL of document 1 is "www.google.com" then
        -- do something
    end if
end tell