Tampermonkey脚本在页面加载之前运行 [英] Tampermonkey script run before page load
问题描述
我需要从html页面中隐藏一个部分:
I need to hide a section from an html page:
<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>
以下代码在Chrome开发人员中正常运行.工具
The following code works fine in Chrome dev. tools
var ibmlogo = document.querySelectorAll('h1.logo.floatLeft');
ibmlogo[1].remove();
但是当我在激活脚本的情况下加载页面时,(h1)部分不会消失. 我相信这是因为在脚本运行时,尚未完成DOM的加载,因此脚本无法找到选择器.
But when I load the page with the script active, the section (h1) won't disappear. I believe this is because when the script runs, the DOM has not been completed loaded yet, hence the script fails to find the selector.
我尝试了许多不同的操作(例如window.onLoad),但是我的脚本仍然无效.上一次尝试(失败)如下:
I have tried many different things (e.g. window.onLoad) but still my script is not effective. Last attempt (failed) is the following:
var logo = document.querySelectorAll('h1.logo.floatLeft');
logo.onload = function() {removeLogo()};
function removeLogo(){
console.log("### logo array lenght: " + logo.length);
logo[1].remove();
};
推荐答案
必需:
-
用户脚本元数据块中的
@run-at: document-start in userscript metablock.
// ==UserScript==
..............
// @run-at document-start
..............
// ==/UserScript==
现在有了以上选项,您可以选择:
Now with the above your options are:
-
简单地注入隐藏徽标的样式:
Simply inject a style that hides the logo:
(document.head || document.documentElement).insertAdjacentHTML('beforeend',
'<style>h1.logo.floatLeft { display: none!important; }</style>');
使用 MutationObserver 检测并删除元素添加到DOM中之后.
Use MutationObserver to detect and delete the element immediately after it's added into DOM.
- Modify elements immediately (not after page completely loads)?
- How to change the HTML content as it's loading on the page ("rare elements" code)
- Performance of MutationObserver to detect nodes in entire 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
这篇关于Tampermonkey脚本在页面加载之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!