简体   繁体   中英

Use Javascript to click link on non-active Chrome tab

I'm trying to use Javascript to click a link on a non-active Chrome tab. I started with this script:

document.getElementById('extractResults').click();

I've found that this script works when I'm currently on the right tab and window, but when I navigate to a different tab or window, it doesn't work.

This is the closest I've come so far, but just can't get it to work!

set tabName to "Name of Tab"
set javascriptStr to "document.getElementById('ID of Link').click();"

tell application "Google Chrome"

  set myTab to tabs of windows whose title is tabName

  repeat with i in myTab
    if (contents of i) = {} then set contents of i to 0
  end repeat

  set myTab to lists of myTab

  if length of myTab = 1 then
    set myTab to item 1 of myTab
    if length of myTab = 1 then
      set myTab to item 1 of myTab
      tell myTab to execute javascript javascriptStr
    end if
  end if
end tell

Unless the two different web pages in the two different tabs have some relationship to each other, it will explicitly not be allowed because it would be a serious security vulnerability.

Imagine the security and privacy issues I'd have if I visited your web site and you had code to iterate and interact with any other tabs I happened to have open in my browser!

However, your pages can interact if they have a relationship. For example, if one tab was opened by a link from the page in the other tab. In this case, your code that does the opening would have to save a reference to the window variable of the page it opened.

You would then be able to call myOtherWindow.document.getElemetnId() and (for the most part) interact with it just as you do the current page.

See: https://developer.mozilla.org/en-US/docs/Web/API/Window/open

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM