AppleScript & Javascript change text colour on safari

applescriptjavascriptsafari

I'm not sure if this is possible but let's say I have a few variables :

var1 "text1'
var2 "2018"
var3 "demo@apple.com"

Can I make Applescript to found every instance of this text on Safari (any tab) and change the colour of the text? (

"document.getElementById("foundhtmlhere").style.color = "#ff0000";"

or

document.querySelector("td > a").style.backgroundColor = "red";

I'm sure there is a better option, perhaps using JavaScript String search() / selector but I'm still have to go through this.
I guess I can search within the body using this, then maybe using text delimiter ? I'm a bit lost

 tell application "Safari"
    tell document 1
        set body to do JavaScript "document.body.innerHTML"
        set body to do JavaScript "document.getElementsByTagName('body').item(0).innerHTML"
    end tell
end tell
return body

Best Answer

You can use the window.find('someString', false or true) command to search some string in the text of the document.

The second parameter of the command, if true, specifies a case-sensitive search.

Use the document.execCommand('HiliteColor', false, someColor) command to change the background color of the founded text.


Here's the sample script, tested on Sierra.

set myList to {"text1", "2018", "demo@apple.com"}

tell application "Safari"
    -- to change the color,  set the 'document.designMode' to on
    -- get the scroll position of the document, because the 'window.find()' command change the scroll position when it select the founded string
    set scrollPos to do JavaScript "document.designMode = 'on'; [window.pageXOffset.toString(),window.pageYOffset.toString()]" in document 1

    repeat with thisText in myList
        do JavaScript "var sel = window.getSelection();
                sel.collapse(document.body, 0);//------    To start at the beginning of the document, not after the selectioned text
                while (window.find('" & thisText & "', true)) {document.execCommand('HiliteColor', false, '#ff0000');}
                sel.collapseToEnd()" in document 1
    end repeat

    -- restore the scroll position
    do JavaScript "document.designMode = 'off';  window.scrollTo(" & (item 1 of scrollPos) & ", " & (item 2 of scrollPos) & ")" in document 1
end tell