window.location改变后如何持久化MutationObserver?

问题描述 投票:0回答:1

假设我正在使用

document
观察
MutationObserver

let mutationObserver = new MutationObserver(mutations => {
...
});

mutationObserver.observe(document, {
    attributes: false,
    childList: true,
    characterData: false,
    subtree: true
});

在此之后,假设我正在使用以下方式加载新的 URL:

window.location = newUrl;
  1. 之前的

    MutationObserver
    会被销毁,这是预期的行为吗?

  2. URL改变后有没有办法持久化

    MutationObserver

如果没有,我可以使用另一种方法来维持

MutationObserver
吗?

javascript dom mutation-observers
1个回答
0
投票

MutationObserver 本身不支持持久化。 如果您需要实现您想要的功能,也许您可以尝试:

  1. 水疗。
  2. 使用
    localstorag
    e 或
    indexdb
    ,这段代码可能是一个想法
// create MutationObserver instance
const observer = new MutationObserver(mutations => {
  // change handler insert data to localstorage
  mutations.forEach(mutation => {
    localStorage.setItem('mutationData', JSON.stringify(mutation));
  });
});


const targetNode = document.getElementById('target_id');
const config = { attributes: true, childList: true, subtree: true };
observer.observe(targetNode, config);

// url change handler. (use history.pushState,popstate...)
window.addEventListener('popstate', function(event) {
  // get localstorage data
  const savedMutationData = localStorage.getItem('mutationData');
  
  if (savedMutationData) {
    // Assuming you want to process these change data under a new URL, use this data based on your specific business needs
    const mutationObj = JSON.parse(savedMutationData);
    console.log('mutationObj:', mutationObj); 
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.