javascript - 如何在不将元素替换为其克隆的情况下断开匿名 MutationObserver 与文档元素的连接?

标签 javascript mutation-observers

在制作一个应该更改多个文档元素属性的 tampermonkey 脚本时,我遇到了一个使用事件监听器来防止对该属性进行任何更改的站点。为了应对这种行为,我可以用它们的克隆替换元素,如下所示:

const map = new Map();

function read() {
    for (let image of [...document.getElementsByTagName('img')]) {
        const clone = image.cloneNode(/* with children */true);
        // TODO: modify the clone
        map.set(image, clone);
    }
}

read();

function write() {
    for (let [image, clone] of map) {
        image.parentNode.replaceChild(clone, image);
    }
}

write();

map.clear();

但这种方法存在一个问题:浏览器(Chrome 71)在运行结束时会重新计算样式,如果元素数量很大(10 个元素 - 无抖动,100 个元素 - 垃圾),有时会抖动布局。我尝试使用请求的动画帧修改写入函数中的循环:

window.requestAnimationFrame(document.replaceChild.bind(image.parentNode, clone, image));

但它仍然会影响布局。 试图在循环中插入暂停:

async function write() {
  for (let [image, clone] of map) {
    await new Promise(window.requestAnimationFrame);
    image.parentNode.replaceChild(clone, image);
  }
}

没有变化。尝试将元素数组分成小块并操作每个 block ,但浏览器最终仍然懒惰地重新计算样式并扰乱布局。 因此,不是用它的克隆替换每个元素,我可以用类似的东西删除每个事件监听器:

for (let image of [...document.getElementsByTagName('img')]) {
  const listeners = getEventListeners(image);
  for (let event_type in listeners) {
    for (let event of listeners[event_type]) {
      image.removeEventListener(event.type, event.listener, event.useCapture);
    }
  }
}

虽然这解决了问题,但问题仍然存在:如果站点不使用事件监听器,而是使用 MutationObserver 来防止修改文档元素怎么办?有没有一种方法可以删除 MutationObserver 而无需用其克隆替换文档元素?

虽然我知道修改很多元素的属性仍然会强制浏览器重排,但我的问题仍然存在。

最佳答案

无法断开匿名 MutationObserver 的连接,但这并不意味着没有其他解决方案。

我相信您不需要更改页面上的所有链接。
您只需要拦截用户会尝试访问的一个链接。

请看下面的片段。

我们想改变 href 属性,它被观察者捕获了:

// anonymous observer:
(new MutationObserver(function(mutationsList, observer) {
  for (var mutation of mutationsList) {
    if (
      mutation.type == 'attributes' &&
      mutation.target.href !== 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
    ) {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
      mutation.target.href = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
    }
  }
}))
.observe(
  document.querySelector('html'), {
    attributes: true,
    subtree: true
  }
);

document.querySelectorAll('a').forEach(function(a) {
  a.href = 'https://yastatic.net/www/_/x/Q/xk8YidkhGjIGOrFm_dL5781YA.svg';
});
<a href="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png">Google</a>

为避免这种情况,请为链接设置事件监听器,并在单击 时更改location.href(或打开新选项卡或窗口)而不是更改a .href:

// anonymous observer:
(new MutationObserver(function(mutationsList, observer) {
  for (var mutation of mutationsList) {
    if (
      mutation.type == 'attributes' &&
      mutation.target.href !== 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
    ) {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
      mutation.target.href = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png'
    }
  }
}))
.observe(
  document.querySelector('html'), {
    attributes: true,
    subtree: true
  }
);

document.querySelectorAll('a').forEach(function(a) {
  a.addEventListener('click', function(e) {
    e.preventDefault();
    location.href = 'https://yastatic.net/www/_/x/Q/xk8YidkhGjIGOrFm_dL5781YA.svg';
  });
});
<a href="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png">Google</a>

关于javascript - 如何在不将元素替换为其克隆的情况下断开匿名 MutationObserver 与文档元素的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54369597/

相关文章:

javascript - 有什么方法可以使用 MutationObserver 来监视带有指定选择器的元素的插入?

Dart Polymer 1.0 有没有办法在客户端和服务器端使用一个 "refectable"类?

jquery - 使用 MutationObserver 比较新旧文本内容

javascript - 如何将2个数组复制到1个数组中?

javascript - 使用 jQuery foreach 并将 "<li><a hef=' #'>text</a></li>"附加到 "<ul>"并附加

php - 在单页网站中使用 jquery ajax 加载页面时显示进度条

javascript - Swiper 观察者随机延迟

javascript - 使用 && 代替 IF 语句

javascript - 如何将选择选项设置为等于 innerHTML

javascript - 从 MutationObserver 的突变编辑 DOM 中的元素