AppleScript : do JS on different Safari windows I'm using some script which basically get text from safari, click button and fill up textfield.

e.g :

tell application "Safari"
    set texttograb to do JavaScript "document.getElementsByClassName('the_variable_as_text')[0].value;" in document 1
    do JavaScript "document.getElementsByClassName('text-entry')[0].value=" &amp; quoted form of myText in last tab of window 1
    do JavaScript "document.getElementsByClassName('Approve-button')[0].click();" in last tab of window 1
end tell


This work perfectly but I have a change in my workflow and I need to use different safari window.

How can I refer one javascript to one specific safari window and the other to a different window.
Especially when some tab might have the same URL/Name ?

I remember seeing that a while back (when the tab happen to have the same name but I never manage to run a script which refer to the window id

Otherwise I suppose I can use another web browser (e.g one safari the second safari technology preview) as a workaround but that not really ideal and limit to two windows

any idea how can I found the window ID and refer to it in AppleScript/JS ?
It's not the best (won't work if the same tab is open in different windows) but This seems to work 

set searchpat to "My Tab"
tell application "Safari"
    set winlist to every window
    set winmatchlist to {}
    set tabmatchlist to {}
    set tabnamematchlist to {}
    repeat with win in winlist
        set ok to true
        try
            set tablist to every tab of win
        on error errmsg
            set ok to false
        end try
        if ok then
            repeat with t in tablist
                if searchpat is in (name of t as string) then
                    set end of winmatchlist to win
                    set end of tabmatchlist to t
                    set end of tabnamematchlist to (id of win as string) &amp; "." &amp; 1 &amp; ".  " &amp; (name of t as string)
                    set theWindowID to (id of win as string)
                    ##return (index of t as string)
                    --display dialog name of t as string                    
                end if
            end repeat
        end if
    end repeat

    set w to item 1 of winmatchlist
    set t to item 1 of tabmatchlist

    set current tab of w to t
    set index of w to 1

end tell


then I can refer the window using theWindowID 

e.g:

tell application "Safari" to tell window id theWindowID to set current tab to tab 1


or 

do JavaScript ResolutionPopUp in tab 1 of window id theWindowID


(I'm referring the tab manually)