如何用Tampermonkey稳定在任意页面顶部添加工具栏DIV?
稳定的页面顶部工具栏插入方案
针对未知页面结构下工具栏被动态body样式覆盖的问题,结合CSS优先级、DOM监听和插入时机优化,给出以下稳定方案:
1. 给工具栏设置强制优先级的CSS样式
直接给工具栏元素添加高权重样式,确保不会被页面动态样式覆盖:
.custom-toolbar { position: fixed !important; top: 0 !important; left: 0 !important; width: 100% !important; z-index: 999999 !important; /* 用足够大的值确保层级最高 */ background-color: #ffffff !important; border-bottom: 1px solid #e0e0e0 !important; padding: 10px 20px !important; box-sizing: border-box !important; }
注:
!important用于强制覆盖页面中可能存在的同属性高优先级样式,z-index设为超大值避免被其他固定定位元素遮挡。
2. 结合MutationObserver处理动态DOM和样式变化
页面的body类、子元素可能会动态更新,通过监听这些变化,确保工具栏始终处于body最顶部:
// 创建工具栏元素 const toolbar = document.createElement('div'); toolbar.className = 'custom-toolbar'; toolbar.innerHTML = '<span>实时演示工具栏</span>'; // 初始插入到body最前端 document.body.insertBefore(toolbar, document.body.firstChild); // 监听body的类属性变化 const bodyAttrObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.attributeName === 'class') { // 确保工具栏始终在body第一个子节点位置 if (document.body.firstChild !== toolbar) { document.body.insertBefore(toolbar, document.body.firstChild); } // 强制重置关键样式,防止被动态样式覆盖 Object.assign(toolbar.style, { position: 'fixed', top: '0', left: '0', width: '100%', zIndex: '999999' }); } }); }); bodyAttrObserver.observe(document.body, { attributes: true }); // 监听body子元素变化,防止新插入的元素挤到工具栏前面 const bodyChildObserver = new MutationObserver((mutations) => { mutations.forEach(mutation => { if (mutation.addedNodes.length > 0 && document.body.firstChild !== toolbar) { document.body.insertBefore(toolbar, document.body.firstChild); } }); }); bodyChildObserver.observe(document.body, { childList: true });
3. 调整Tampermonkey运行时机
不要仅依赖document-end,改用更早的时机插入工具栏,抢占DOM位置:
// @run-at document-body
注:
document-body会在body元素刚创建完成时立即执行脚本,比document-end更早插入工具栏,避免后续动态元素或样式的影响。
额外适配建议
- iframe场景:如果脚本可能在iframe中运行,可通过
window.top !== window.self判断,选择操作window.top.document.body或当前document。 - CSP限制:部分页面有内容安全策略,Tampermonkey通常会自动适配,若遇到执行失败,可尝试将样式内联到工具栏元素上。
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

