下面是一份完整可用的「immutable-title.js」,复制保存后直接以
<script src="immutable-title.js"></script> 引入即可。
它会立即在页面顶部插入一个 H1 标题,并通过 MutationObserver 监听确保文字、样式以及是否存在于文档中都不会被后续脚本或样式表篡改 / 覆盖。
/* immutable-title.js */
(() => {
/* === 一、核心常量 === */
const ORIGINAL_TEXT = '这是一个不可修改的标题';
const ORIGINAL_STYLE = {
margin: '0',
padding: '12px',
fontSize: '24px',
color: '#fff',
backgroundColor: '#007acc',
textAlign: 'center',
userSelect: 'none',
};
/* === 二、创建并插入标题 === */
const header = document.createElement('h1');
header.textContent = ORIGINAL_TEXT;
header.setAttribute('data-immutable-title', 'true');
// 逐条动态注入样式(不拼接 <style> 或 CSS 字符串)
Object.entries(ORIGINAL_STYLE).forEach(([prop, value]) => {
header.style.setProperty(prop, value, 'important'); // 添加 !important 提高优先级
});
// 确保在 <body> 出现后插入
const ensureInsert = () => {
if (!header.isConnected && document.body) {
document.body.prepend(header);
}
};
document.body ? ensureInsert() : document.addEventListener('DOMContentLoaded', ensureInsert);
/* === 三、MutationObserver:防篡改逻辑 === */
// 1. 观察标题本身(文本、属性、内联样式等)
const headerObserver = new MutationObserver(() => {
// 文字被改?——还原
if (header.textContent !== ORIGINAL_TEXT) header.textContent = ORIGINAL_TEXT;
// 样式被改?——逐项还原
Object.entries(ORIGINAL_STYLE).forEach(([prop, value]) => {
const current = header.style.getPropertyValue(prop);
if (current !== value) header.style.setProperty(prop, value, 'important');
});
});
headerObserver.observe(header, {
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ['style', 'class', 'id'],
});
// 2. 观察整个 document,防止标题被移除
const removalObserver = new MutationObserver(mutations => {
for (const m of mutations) {
m.removedNodes.forEach(node => {
if (node === header) ensureInsert(); // 立即重新挂回去
});
}
});
document.addEventListener('DOMContentLoaded', () => {
removalObserver.observe(document.body, {childList: true, subtree: true});
});
})();
使用说明
- 将以上代码保存为
immutable-title.js。
- 在任意 HTML 中引入:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<script src="immutable-title.js"></script>
</body>
</html>
效果
• 页面加载时最顶部会出现蓝底白字的 H1 标题。
• 无论后续 JS/DevTools 尝试修改文本、内联样式、class,或直接从 DOM 中删除节点,脚本都会立刻“打回原形”。
• 所有样式均通过 element.style.setProperty 动态逐条注入,完全未使用字符串拼接的 <style> 或 style.textContent。