0

I'm trying to make a user script that gets the first anchor element that has been visited in javascript but for some reason the querySelector isn't working with :visited

const element = document.querySelector("a:visited");
element; // => null

I know there are atleast a couple of visited tags because I inspected the page and there were some css styles using a:visited and those styles were applied, (for example: color: #f5a383;);

The next thing I tried was to get each <a> tags and then find the first one that's computed color value was correct

const elements = document.querySelectorAll("a");
let element = [...elements].find(e => getComputedStyle(e).getPropertyValue("color").trim() === "#f5a383");

But this also didn't get the element

Lastly just to make sure it wasn't the website's fault I made a test project and it still failed: enter image description here

  • Your computed color approach might work but even when you set a css color using hex values it will get returned as RGB (or RGBA in some cases) from browser and never as hex – charlietfl Jul 19 '20 at 20:29
  • `:before` and `:after` are a lot different than `:visited`, things like `:checked` and `:link`, can be queried for since they are just options to check for. As for the computed style approach you are correct, the other reason it didn't work was because the values were all rgb equivalent for white. –  Jul 19 '20 at 20:37

1 Answers1

0

This approach disabled for security reasons.

This has been confirmed in all major browsers: none support querySelector("a:visited") any longer.

As it is possible to retrieve a visitor's history by checking for visited links, certain measures have been taken by browser vendors to prevent this.

Source 1

Source 2


However, there is a workaround without using the :visited selector:

I found a workaround utilising JavaScript LocalStorage

This approach stores links clicked by the user in LocalStorage and adds the class visited to the parent of the <a> element:

function check_visited_links() {
    var visited_links = JSON.parse(localStorage.getItem('visited_links')) || [];
    var links = document.getElementsByTagName('a');
    for (var i = 0; i < links.length; i++) {
        var that = links[i];
        that.onclick = function() {
            var clicked_url = this.href;
            if (visited_links.indexOf(clicked_url) == -1) {
                visited_links.push(clicked_url);
                localStorage.setItem('visited_links', JSON.stringify(visited_links));
            }
        }
        if (visited_links.indexOf(that.href) !== -1) {
            that.parentNode.className += ' visited';
        }
    }
}

Source

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42