Javascript 在页面加载之前运行脚本
我需要从html页面隐藏一个部分:Javascript 在页面加载之前运行脚本,javascript,html,tampermonkey,Javascript,Html,Tampermonkey,我需要从html页面隐藏一个部分: <h1 data-ng-show="!menuPinned && !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX </span><span style="font-weight: bold;">XXX </span><span>XXXXX</
<h1 data-ng-show="!menuPinned && !isSaaS" class="logo floatLeft" aria-hidden="false"><span>XXX </span><span style="font-weight: bold;">XXX </span><span>XXXXX</span></h1>
但是当我在脚本处于活动状态的情况下加载页面时,部分(h1)不会消失。
我认为这是因为当脚本运行时,DOM尚未完成加载,因此脚本无法找到选择器
我尝试了许多不同的方法(例如window.onLoad),但我的脚本仍然无效。最后一次尝试(失败)如下:
var logo = document.querySelectorAll('h1.logo.floatLeft');
logo.onload = function() {removeLogo()};
function removeLogo(){
console.log("### logo array lenght: " + logo.length);
logo[1].remove();
};
必填项:
- 在用户脚本元块中
// ==UserScript== .............. // @run-at document-start .............. // ==/UserScript==
(document.head || document.documentElement).insertAdjacentHTML('beforeend',
'<style>h1.logo.floatLeft { display: none!important; }</style>');
如果用户风格(例如使用)为
h1.logo.floatLeft{display:none;}
的话,这不是很好吗?谢谢@woxxom,即使我不太明白怎么做,第一个选项也能起作用。当运行my元素的脚本不存在时(我使用document.querySelectorAll进行了测试,那么insertAdjacentHTML如何在一个不存在的节点中注入内容?如果它创建了一个节点,当页面最终加载时,它不应该覆盖我注入的元素?Hi不能做第二个选择(更喜欢)在你的代码中,我在倒数第二行发现了一个语法错误(不明白为什么)。然后我尝试了mozilla网站上的示例,代码失败了,因为目标不是节点,并检查了它,当我创建目标时,元素不存在(我甚至尝试了“html”)而且目标总是空的..干杯1.这是CSS表单的作用2.代码应该按原样工作,不要更改观察中的文档参数。总之,我不是通灵者,所以我不能告诉你浏览器中发生了什么
(document.head || document.documentElement).insertAdjacentHTML('beforeend',
'<style>h1.logo.floatLeft { display: none!important; }</style>');
new MutationObserver(function(mutations) {
// check at least two H1 exist using the extremely fast getElementsByTagName
// which is faster than enumerating all the added nodes in mutations
if (document.getElementsByTagName('h1')[1]) {
var ibmlogo = document.querySelectorAll('h1.logo.floatLeft')[1];
if (ibmlogo) {
ibmlogo.remove();
this.disconnect(); // disconnect the observer
}
}
}).observe(document, {childList: true, subtree: true});
// the above observes added/removed nodes on all descendants recursively