检测来自 Tampermonkey 的react事件

IT技术 reactjs greasemonkey tampermonkey
2021-05-14 06:59:47

我正在使用 Tampermonkey 增强 React 前端,通过添加高亮显示网格中的光标位置,并允许用户直接输入数据,而不是输入数据。

移动 2 或 3 次光标或输入数据后,网格会刷新或更新 - 无页面更改 - 并取消我设置的突出显示。

我想捕捉刷新/更新并重置突出显示。

我是菜鸟。。

网络选项卡显示发布事件,所以我尝试了https://jsbin.com/dixelocazo/edit?js,console var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send;

尝试使用 POST 事件来检测刷新。没有快乐!

我还查看了 ajax 事件。

没有运气 :(

有人可以在这里指出我正确的方向吗?

一旦我捕捉到事件,我就可以重置突出显示以解决问题

1个回答

由于用户脚本通常在沙箱中运行,默认情况下无法直接使用 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 的性能