简体   繁体   English

获取 javascript 中访问过的第一个锚元素

[英]Getting the first Anchor Element that has been visited in javascript

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我正在尝试制作一个用户脚本,以获取在 javascript 中访问过的第一个锚元素,但由于某种原因, querySelector无法使用: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; );我知道至少有几个访问过的标签,因为我检查了页面并且有一些 css styles 使用a:visited和那些 stylesa38 应用了color: #f5a383;例如:#f)

The next thing I tried was to get each <a> tags and then find the first one that's computed color value was correct我尝试的下一件事是获取每个<a>标签,然后找到第一个计算出的颜色值是正确的

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:最后只是为了确保这不是网站的错,我做了一个测试项目,但它仍然失败: 在此处输入图像描述

This approach disabled for security reasons .出于安全原因禁用此方法。

This has been confirmed in all major browsers: none support querySelector("a:visited") any longer.这已在所有主流浏览器中得到证实:不再支持querySelector("a:visited")

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 来源 1

Source 2来源 2


However, there is a workaround without using the :visited selector:但是,有一个不使用:visited选择器的解决方法:

I found a workaround utilising JavaScript LocalStorage我找到了一个使用 JavaScript LocalStorage的解决方法

This approach stores links clicked by the user in LocalStorage and adds the class visited to the parent of the <a> element:这种方法将用户点击的链接存储在LocalStorage中,并将visited的 class 添加到<a>元素的父元素中:

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资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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