假设我正在使用
document
观察 MutationObserver
:
let mutationObserver = new MutationObserver(mutations => {
...
});
mutationObserver.observe(document, {
attributes: false,
childList: true,
characterData: false,
subtree: true
});
在此之后,假设我正在使用以下方式加载新的 URL:
window.location = newUrl;
之前的
MutationObserver
会被销毁,这是预期的行为吗?
URL改变后有没有办法持久化
MutationObserver
?
如果没有,我可以使用另一种方法来维持
MutationObserver
吗?
MutationObserver 本身不支持持久化。 如果您需要实现您想要的功能,也许您可以尝试:
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);
}
});