AppleScript for Safari – How to Execute JavaScript on Every Tab/Window

applescriptsafari

How to run JavaScript in every safari TAB?

I used to have a script with find a specific tab and run javascript but I have some issue and I was wondering how can I simply run some JavaScript in every tab and window (safari) instead.

tell application "Safari" to tell document 1 to do JavaScript ¬
    "document.getElementsByClassName('Demo')[0].click();"

I though running a script to tell how many tab and create a loops but that doesn't work as I have multiple window of safari

Best Answer

Using the Ask Question button that's in the upper right hand corner of the page, like in this question, and having multiple windows each with multiple tabs to a Ask Different web page, as well as some non-related pages...

The following example AppleScript code clicks the Ask Question button on every page having the button. It doesn't matter what window or tab has focus, the button on all that have it gets clicked.

Example AppleScript code:

tell application "Safari" to tell tabs of windows to ¬
    do JavaScript "document.getElementsByClassName('ws-nowrap s-btn s-btn__primary')[0].click();"