SoFunction
Updated on 2025-03-01

JS dynamically modify the background color instance code of web page body

The default background color of most web pages is white, which I personally feel is more dazzling, so I wrote a JS script to change the background color of the body part. The code is as follows:

// ==UserScript==
// @name    ChangeBackgroundColor
// @namespace  tingl
// @include   *
// @version   1
// @grant    none
// ==/UserScript==
(function () {
 'use strict';
 var color = '#ececec';
 var style;
 function createStyle() {
  style = ('style');
   = 'text/css';
   = 'body {background-color: ' + color + ' !important;}';
 }
 function changeBackgroundColor() {
  if(!) (style);
 }
 createStyle();
 changeBackgroundColor();
 ("DOMNodeRemoved",changeBackgroundColor);
}) ()

The code is relatively simple. It directly creates a css style rule on the body and adds it to the head. If the web page content changes or is updated asynchronously, it will be added to the head again through the event listening mechanism.

Since the background color on the body is simply changed, the scope of application of scripts is limited.

Summarize

The above is the example code of JS dynamically modifying the background color of the web page body introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!