Search code examples
javascripthtmlcsstampermonkey

How can i href a local file using tampermonkey?


I want to replace a site's CSS file URL through href, i know it's possible to reference external links containing css but what about a local file instead?

document.querySelector("head > link:nth-child(7)").href = "http://example.com/style.css"

Solution

  • One option would be for the local file to be a script, perhaps one that assigns the desired CSS text to a window property, which can then be retrieved inside your userscript. For example:

    // ==UserScript==
    // @name         local
    // @match        https://example.com
    // @require      file:///C:/local.js
    // ==/UserScript==
    
    document.head.appendChild(document.createElement('style'))
      .textContent = window.cssTextFromLocal;
    

    and

    // local.js
    window.cssTextFromLocal = `
      body {
        background-color: green;
      }
    `;
    

    enter image description here

    Make sure to permit local file access.

    Of course, if you want to do this unconditionally (on every page load, regardless), there's no need for inter-script communication, and you can insert the <style> into the DOM inside local.js.