Search code examples
greasemonkeytampermonkey

How can I get Tampermoney to set the color of visited links?


HackerNews (https://news.ycombinator.com/) styles visited links with a similar color to unvisited links. I want to style the visited links a contrasting color.

I'm new to Tampermonkey (and web/js in general). I did search and the closest I found was this this code, which I modified. Sadly it doesn't appear to have any affect on visited links' color.

// ==UserScript==
// @name          Hacker News Visited Link Highlighter
// @description   Highlights visited links on Hacker News with a different color
// @namespace     http://tampermonkey.net/
// @match         https://news.ycombinator.com/*
// @version       2024-01-13
// ==/UserScript==
// History:
// --------
// 2024-01-13  First version

(function () {

   GM_addStyle("a:visited { color: #FF0084 }");

})();

Solution

  • You can either just add the line @grant GM_addStyle to your userscript header, like so:

    // ==UserScript==
    // @name          Hacker News Visited Link Highlighter
    // @description   Highlights visited links on Hacker News with a different color
    // @namespace     http://tampermonkey.net/
    // @match         https://news.ycombinator.com/*
    // @version       2024-01-13
    // @grant         GM_addStyle
    // ==/UserScript==
    

    Or you can also just inject the desired HTML yourself, like this:

    // ==UserScript==
    // @name          Hacker News Visited Link Highlighter
    // @description   Highlights visited links on Hacker News with a different color
    // @namespace     http://tampermonkey.net/
    // @match         https://news.ycombinator.com/*
    // @version       2024-01-13
    // ==/UserScript==
    
    (function() {
        'use strict';
        document.querySelector('body').insertAdjacentHTML('beforeend', init_css() );
    
        setTimeout( () => {
            //The setTimeout ensures the new element exists in the DOM 
            //before trying to attach this event handler
            document.querySelector('#myDiv').addEventListener('click', () => {
                alert('You clicked me');
            });
        },100);
    
        function init_css(){
            return `
            <div id="myDiv">Here is my div</div>
            <style id="myInitCss">
                a:visited { color: #FF0084; }
                #myDiv{position:absolute;top:0;left:0;padding:50px;font-size:18px;color:blue;background:wheat;z-index:99999999999;}
            </style>
            `;
        }
    })();
    
    

    Using the 2nd method also demonstrates how you can add things like new DIVs, buttons, etc to the web page also. (Of course, you would remove the #myDiv element and associated style if not desired - that bit is there by way of example only)