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

如何在指定节点下添加innerHTML并编写用户脚本使修改在页面刷新后保留

Hey there! Let's work through your two scripting questions— I’ve been stuck on similar stuff before, so I feel your confusion 😊

1. How to Add innerHTML to a Specific Node

First, let’s cover the basics of injecting content into a target node. There are a few ways to do this, depending on whether you want to replace existing content or add to it:

  • Replace the node’s entire content:
    Use innerHTML directly to overwrite everything inside the node:

    // First, grab your target node using a selector (ID, class, etc.)
    const targetNode = document.querySelector('#your-target-id');
    if (targetNode) {
        targetNode.innerHTML = '<p>New content that replaces everything inside the node</p>';
    }
    
  • Append content to the end of the node:
    If you want to keep existing content and add more, use += (though note this can sometimes break existing event listeners on child elements):

    targetNode.innerHTML += '<p>Extra content added to the end</p>';
    
  • Safer append (preserves event listeners):
    A better option for adding content without messing up existing elements is insertAdjacentHTML:

    // 'beforeend' adds the content as the last child of the target node
    targetNode.insertAdjacentHTML('beforeend', '<p>Safely added content that won’t break existing listeners</p>');
    

    You can also use other positions like beforebegin, afterbegin, or afterend depending on where you want the content placed.

2. Making Changes Persist After Page Refresh with a User Script

When you use the browser Inspector to modify the DOM, those changes only exist in your current session— refreshing resets everything to the server’s original HTML. To make the changes stick, you’ll need a user script (tools like Tampermonkey or Greasemonkey let you run custom JS on specific sites automatically).

Here’s a complete script example that adds your custom content every time the page loads (and even handles dynamic content that loads after the initial page load):

// ==UserScript==
// @name         Persist Custom InnerHTML
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Adds persistent custom content to a specific node on page load
// @author       Your Name
// @match        https://your-target-website.com/*  // Replace this with the site URL you're modifying
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Function to add your custom content
    function injectCustomContent() {
        // Replace this selector with the one for your target node (use Inspector to find it!)
        const targetNode = document.querySelector('#your-target-node-selector');
        
        if (targetNode) {
            // Add your desired innerHTML here
            const customContent = '<div class="my-custom-content">This stays even after refresh!</div>';
            targetNode.insertAdjacentHTML('beforeend', customContent);
        }
    }

    // Run when the initial page finishes loading
    window.addEventListener('load', injectCustomContent);

    // If the site loads content dynamically (like a single-page app), listen for DOM changes
    const domObserver = new MutationObserver((mutations) => {
        mutations.forEach(mutation => {
            // Check if new nodes were added to the DOM
            if (mutation.addedNodes.length > 0) {
                injectCustomContent();
            }
        });
    });

    // Observe changes to the entire body (adjust if you only need to watch a specific area)
    domObserver.observe(document.body, { childList: true, subtree: true });
})();

Key Notes for This Script:

  • Replace @match with the exact URL (or URL pattern) of the site you’re modifying— this ensures the script only runs where you want it to.
  • Update the document.querySelector selector to match your target node (use the Inspector to copy the selector right from the element!).
  • The MutationObserver part is for sites that load content dynamically (e.g., scrolling loads more posts, or content loads via AJAX). If your target node exists on the initial page load, you can skip this part if you want.

Bonus: Saving Dynamic User Changes

If you want users to edit the content and have those edits persist, use localStorage to save the content:

// Modify the inject function to load saved content
function injectCustomContent() {
    const targetNode = document.querySelector('#your-target-node-selector');
    if (targetNode) {
        // Load saved content from localStorage, or use a default if nothing's saved
        const savedContent = localStorage.getItem('persistentCustomContent') || '<div>Default content</div>';
        targetNode.insertAdjacentHTML('beforeend', savedContent);
    }
}

// Add a function to save content when it's edited (e.g., on a button click)
function saveCustomContent() {
    const customContentElement = document.querySelector('.my-custom-content');
    if (customContentElement) {
        localStorage.setItem('persistentCustomContent', customContentElement.innerHTML);
    }
}

Just add a button or event listener to trigger saveCustomContent() when the user makes changes, and the content will stay even after closing and reopening the browser!

内容的提问来源于stack exchange,提问作者HEAT SINK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:42:42