如何使用JavaScript禁用HTML中的script标签或修改其src/type属性(无法添加ID场景)
Got it, let's work through this problem step by step. Since we can't add an ID to that specific script tag, we'll target it using its existing type and src attributes—here are reliable approaches for each of your goals:
The easiest way to disable a script without removing it is to change its type to a value browsers don't recognize as executable (like text/plain). This tells the browser to ignore the script instead of running it. You can also remove the script entirely if it hasn't loaded yet.
// Target the script by matching its exact type and src attributes const targetScript = document.querySelector('script[type="text/javascript"][src="./1.js.download"]'); if (targetScript) { // Option 1: Change type to non-executable format targetScript.type = 'text/plain'; // Option 2: Remove the script from the DOM (only works if it hasn't executed yet) // targetScript.remove(); }
Critical Note: This code must run before the target script loads or executes. Place your script in the <head> section (before the target script) or directly immediately above the target script tag.
If you want to swap out the script file entirely, target the tag and update its src property:
const targetScript = document.querySelector('script[type="text/javascript"][src="./1.js.download"]'); if (targetScript) { // Replace with your desired script URL targetScript.src = './your-custom-script.js'; }
Again, timing matters here—modify the src before the browser starts downloading the original script.
If you need to change the script's execution type (instead of disabling it), you can update the type to valid values like module (for ES modules) or text/babel (if using Babel, assuming you have the necessary loader):
const targetScript = document.querySelector('script[type="text/javascript"][src="./1.js.download"]'); if (targetScript) { // Change to ES module type, for example targetScript.type = 'module'; }
If the target script is added to the DOM after page load (dynamically), use a MutationObserver to catch it as soon as it's inserted and modify it before it runs:
// Set up observer to watch for new nodes in the DOM const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { // Check each newly added node const targetScript = Array.from(mutation.addedNodes).find(node => node.tagName === 'SCRIPT' && node.type === 'text/javascript' && node.src === './1.js.download' ); if (targetScript) { // Perform your action (disable, modify src/type) targetScript.type = 'text/plain'; // Stop observing once we've found and modified the script observer.disconnect(); } }); }); // Start observing the entire body for changes observer.observe(document.body, { childList: true, subtree: true });
This observer will watch for any new nodes added to the DOM, find the target script, and apply your changes immediately—before it has a chance to execute.
内容的提问来源于stack exchange,提问作者user15307792

