Applescript to set non focus tab in safari

I made a script to find an tab based on it’s URL and set a new URL (the tab is not focused)

tell application "Safari"     set topWindows to every window whose name is not ""     set numWindows to the number of topWindows     set didFind to false     set targetUrl to ""      repeat with x from 1 to numWindows         set numTabs to the number of tabs in window x         repeat with y from 1 to numTabs             set tabUrl to the URL of tab y of window x             if tabUrl contains targetUrl then                 set didFind to true                 tell window x to set current tab to tab y             end if         end repeat     end repeat  end tell  set myLink to ""   tell application "Safari"     tell front window         set URL of tab y to myLink     end tell end tell 

The correct tab is found, the index is found, but it’s seems to always open the URL in a the latest tab instead of the existing tab

how can I fix this?