Gio*_*lli 9 html javascript 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</span></h1>
Run Code Online (Sandbox Code Playgroud)
以下代码在Chrome dev中正常运行.工具
var ibmlogo = document.querySelectorAll('h1.logo.floatLeft');
ibmlogo[1].remove();
Run Code Online (Sandbox Code Playgroud)
但是当我在脚本处于活动状态时加载页面时,部分(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();
};
Run Code Online (Sandbox Code Playgroud)
有什么建议?谢谢Giovanni
wOx*_*xOm 21
需要:
@ run-at:在documentcript metablock中的document-start.
// ==UserScript==
..............
// @run-at document-start
..............
// ==/UserScript==
Run Code Online (Sandbox Code Playgroud)现在有了上述选项,您可以:
只需注入隐藏徽标的样式:
(document.head || document.documentElement).insertAdjacentHTML('beforeend',
'<style>h1.logo.floatLeft { display: none!important; }</style>');
Run Code Online (Sandbox Code Playgroud)使用MutationObserver在元素添加到DOM后立即检测并删除它.
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
Run Code Online (Sandbox Code Playgroud)