从Tampermonkey检测反应事件 [英] Detect react event from Tampermonkey
问题描述
我正在通过Tampermonkey增强React前端,方法是添加突出显示以显示光标在网格中的位置,并允许用户直接输入数据,而不是随后输入数据.
I'm enhancing a React front end with Tampermonkey , by adding highlights to show cursor location in a grid, and allowing users to directly enter data , rather than then enter data.
在移动2或3个光标或输入数据后,网格刷新或更新-没有页面更改-并松开了我设置的突出显示.
After 2 or 3 cursor moves or data entry the grid refreshes or updates - no page change - and looses the highlighting I set up.
我想捕捉刷新/更新并重置突出显示.
I'd like to catch the refresh/update and reset the highlighting.
我是菜鸟.
网络"标签显示了发布事件,因此我尝试了 https://jsbin.com/dixelocazo/edit?js,控制台
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;
The network tab shows post events so I tried https://jsbin.com/dixelocazo/edit?js,console
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;
尝试使用POST事件检测刷新.不高兴!
to try and use POST events to detect the refresh. No joy !
我还查看了ajax事件.
I also looked at ajax events.
没有运气:(
有人可以在这里向我指出正确的方向吗?
Can someone point me in the right direction here ?
一旦捕捉到事件,我便可以重置突出显示以解决问题
Once I catch the event, I can then reset the highlighting to fix the problem
推荐答案
由于用户脚本通常在沙箱中运行,因此默认情况下无法直接使用JavaScript函数或对象,因此您可以执行以下操作:
Since normally the userscripts run in a sandbox, JavaScript functions or objects cannot be used directly by default, here's what you can do:
// @grant none
但是,您将无法使用任何GM功能.
You won't be able to use any GM functions, though.
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的性能.
.surviving-ancestor
means the element that isn't replaced/recreated by the page script. In devtools element inspector it's the one that isn't highlighted temporarily during DOM updates.- See also Performance of MutationObserver.
这篇关于从Tampermonkey检测反应事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!