You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome浏览器中如何为已访问链接添加HTML属性?

识别已访问链接并添加标记的实现方案

核心限制说明

Chrome出于隐私保护目的,对:visited伪类的JS访问做了严格限制:你无法直接通过getComputedStyle获取已访问链接的真实样式,浏览器会返回与未访问链接一致的计算结果,防止脚本窃取用户浏览记录。

可行实现思路

虽然不能直接读取样式,但可以通过隐藏元素对比法间接判断链接是否已访问:

  • 创建两个隐藏的测试<a>元素,分别设置:visited和默认状态的可识别样式(比如不同颜色)
  • 将目标链接的href赋值给两个测试元素,通过对比两者的计算样式差异,判断目标链接是否已访问

Tampermonkey脚本示例

// ==UserScript==
// @name         标记已访问链接
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  给已访问的a标签添加visited属性
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 创建隐藏测试元素,利用:visited允许修改的color属性做区分
    const testVisited = document.createElement('a');
    const testUnvisited = document.createElement('a');
    testVisited.style.cssText = 'position:absolute; left:-9999px; color: #ff0000;';
    testUnvisited.style.cssText = 'position:absolute; left:-9999px; color: #0000ff;';
    document.body.appendChild(testVisited);
    document.body.appendChild(testUnvisited);

    // 遍历页面所有带href的a标签
    document.querySelectorAll('a[href]').forEach(link => {
        testVisited.href = link.href;
        testUnvisited.href = link.href;

        // 对比两个测试元素的计算颜色
        const visitedColor = getComputedStyle(testVisited).color;
        const unvisitedColor = getComputedStyle(testUnvisited).color;

        if (visitedColor !== unvisitedColor) {
            // 已访问,给target属性追加visited标记
            const currentTarget = link.getAttribute('target') || '';
            link.setAttribute('target', currentTarget.trim() + ' visited');
        }
    });

    // 清理测试元素
    document.body.removeChild(testVisited);
    document.body.removeChild(testUnvisited);
})();

关键注意事项

  • 仅能使用浏览器允许:visited修改的属性做对比,比如color、background-color,像width、height这类属性无法通过:visited改变,不能用于判断
  • 跨域链接的判断限制更严格,可能无法得到准确结果
  • 该方法依赖浏览器隐私规则,若后续规则调整,脚本可能失效

内容的提问来源于stack exchange,提问作者丶 Limeー来夢 丶

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:15:52