由于用户脚本通常在沙箱中运行,默认情况下无法直接使用 JavaScript 函数或对象,因此您可以执行以下操作:
禁用沙箱:
// @grant none
但是,您将无法使用任何 GM 功能。
通过 unsafeWindow 在页面上下文中运行:
const __send = unsafeWindow.XMLHttpRequest.prototype.send;
unsafeWindow.XMLHttpRequest.prototype.send = function () {
this.addEventListener('loadend', e => {
console.log('intercepted', e);
}, {once: true});
__send.apply(this, arguments);
};
使用 MutationObserver 检测页面 DOM 的变化:
const observer = new MutationObserver(mutations => {
const matched = [];
for (const {addedNodes} of mutations) {
for (const n of addedNodes) {
if (!n.tagName)
continue;
if (n.matches('.prey:not(.my-highlight)')) {
matched.push(n);
} else if (n.firstElementChild) {
matched.push(...n.querySelectorAll('.prey:not(.my-highlight)'));
}
}
}
// process the matched elements
for (const el of matched) {
el.classList.add('my-highlight');
}
});
observer.observe(document.querySelector('.surviving-ancestor') || document.body, {
subtree: true,
childList: true,
});
.surviving-ancestor表示未被页面脚本替换/重新创建的元素。在 devtools 元素检查器中,它是在 DOM 更新期间暂时未突出显示的元素。
- 另请参阅MutationObserver 的性能。