乐闻世界logo
搜索文章和话题

How to change a class CSS with a Greasemonkey/Tampermonkey script?

1个答案

1

How to use Greasemonkey or Tampermonkey scripts to modify CSS classes.

To modify the CSS styles of a website, we use user script managers like Greasemonkey (for Firefox) or Tampermonkey (for Chrome) to add or modify CSS rules on the webpage. User scripts enable you to run custom JavaScript code when a webpage is loaded by the browser, allowing you to change the appearance and behavior of webpages.

The following is a basic step-by-step guide and example for modifying CSS classes using Tampermonkey:

1. Install the Tampermonkey extension

First, you need to install the Tampermonkey extension in the Chrome browser. This can be downloaded and installed for free from the Chrome Web Store.

2. Create a new user script

After installation, click the Tampermonkey icon in the top-right corner of the browser and select 'Add new script...'.

3. Write a script to modify CSS

In the script editor page, you can input JavaScript code similar to the following to modify the styles of specific CSS classes:

javascript
// ==UserScript== // @name Example to Modify Website Styles // @namespace http://tampermonkey.net/ // @version 1.0 // @description Attempt to modify webpage CSS styles // @author Your Name // @match http://example.com/* // @grant GM_addStyle // ==/UserScript== (function() { 'use strict'; // Add or modify CSS rules GM_addStyle('.your-class-name { background-color: red !important; color: white !important; }'); })();

In this example, the @match directive ensures the script runs only on specific websites (e.g., http://example.com/*). The GM_addStyle function adds new CSS rules, here changing the background color of all elements with the class your-class-name to red and setting the text color to white.

4. Save and test the script

Save your script and visit a matching website to see the effect. If everything is configured correctly, you should observe changes in the styles of the relevant elements.

Using Greasemonkey/Tampermonkey to modify CSS classes offers high flexibility and power. You can adjust and extend these basic steps as needed, such as adding more CSS rules or applying different rules across various websites. I hope this guide is helpful to you! If you have further questions or need more detailed explanations, please feel free to ask.

2024年8月15日 20:32 回复

你的答案