如何在指定节点下添加innerHTML并编写用户脚本使修改在页面刷新后保留
Hey there! Let's work through your two scripting questions— I’ve been stuck on similar stuff before, so I feel your confusion 😊
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:
UseinnerHTMLdirectly 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 isinsertAdjacentHTML:// '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, orafterenddepending on where you want the content placed.
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
@matchwith 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.querySelectorselector to match your target node (use the Inspector to copy the selector right from the element!). - The
MutationObserverpart 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

