Stringify MutationObserver 突变

问题描述

我在整理 a fiddle to help someone learn about mutation observers 时注意到,当您尝试对 MutationRecord 对象进行字符串化时,它在控制台记录时显示为空,MutationRecord 按预期显示

如何将 MutationRecord 字符串化?

JSON.stringify(mutation)

"{}"

console.log(mutation)

[object MutationRecord] {
  addednodes: [object NodeList] {
    0: [object Text] { ... },entries: function entries() { [native code] },forEach: function forEach() { [native code] },item: function item() { [native code] },keys: function keys() { [native code] },length: 1,values: function values() { [native code] }
  },attributeName: null,attributeNamespace: null,nextSibling: null,oldValue: null,prevIoUsSibling: null,removednodes: [object NodeList] {
    0: [object Text] { ... },target: [object HTMLParagraphElement] {
    accessKey: "",addEventListener: function addEventListener() { [native code] },after: function after() { [native code] },align: "",animate: function animate() { [native code] },append: function append() { [native code] },appendChild: function appendChild() { [native code] },ariaAtomic: null,ariaAutoComplete: null,ariaBusy: null,ariaChecked: null,ariaColCount: null,ariaColIndex: null,ariaColSpan: null,ariaCurrent: null,ariaDescription: null,ariadisabled: null,ariaExpanded: null,ariaHasPopup: null,ariaHidden: null,ariaKeyShortcuts: null,ariaLabel: null,ariaLevel: null,ariaLive: null,ariaModal: null,ariaMultiLine: null,ariaMultiSelectable: null,ariaOrientation: null,ariaPlaceholder: null,ariaPosInSet: null,ariapressed: null,ariaReadOnly: null,ariaRelevant: null,ariarequired: null,ariaRoleDescription: null,ariaRowCount: null,ariaRowIndex: null,ariaRowSpan: null,ariaSelected: null,ariaSetSize: null,ariaSort: null,ariaValueMax: null,ariaValueMin: null,ariaValueNow: null,ariaValueText: null,assignedSlot: null,attachInternals: function attachInternals() { [native code] },attachShadow: function attachShadow() { [native code] },ATTRIBUTE_NODE: 2,attributes: [object NamednodeMap] { ... },attributeStyleMap: [object StylePropertyMap] { ... },autocapitalize: "",autofocus: false,baseURI: "https://fiddle.jshell.net/_display/?editor_console=true",before: function before() { [native code] },blur: function blur() { [native code] },CDATA_SECTION_NODE: 4,childElementCount: 0,childNodes: [object NodeList] { ... },children: [object HTMLCollection] { ... },classList: [object DOMTokenList] { ... },className: "",click: function click() { [native code] },clientHeight: 18,clientLeft: 0,clientTop: 0,clientWidth: 824,cloneNode: function cloneNode() { [native code] },closest: function closest() { [native code] },COMMENT_NODE: 8,compareDocumentPosition: function compareDocumentPosition() { [native code] },computedStyleMap: function computedStyleMap() { [native code] },contains: function contains() { [native code] },contentEditable: "inherit",dataset: [object DOMStringMap] { ... },dir: "",dispatchEvent: function dispatchEvent() { [native code] },DOCUMENT_FRAGMENT_NODE: 11,DOCUMENT_NODE: 9,DOCUMENT_POSITION_CONTAINED_BY: 16,DOCUMENT_POSITION_CONTAINS: 8,DOCUMENT_POSITION_disCONNECTED: 1,DOCUMENT_POSITION_FOLLOWING: 4,DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: 32,DOCUMENT_POSITION_PRECEDING: 2,DOCUMENT_TYPE_NODE: 10,draggable: false,ELEMENT_NODE: 1,elementTiming: "",enterKeyHint: "",ENTITY_NODE: 6,ENTITY_REFERENCE_NODE: 5,firstChild: [circular object Text],firstElementChild: null,focus: function focus() { [native code] },getAnimations: function getAnimations() { [native code] },getAttribute: function getAttribute() { [native code] },getAttributeNames: function getAttributeNames() { [native code] },getAttributeNode: function getAttributeNode() { [native code] },getAttributeNodeNS: function getAttributeNodeNS() { [native code] },getAttributeNS: function getAttributeNS() { [native code] },getBoundingClientRect: function getBoundingClientRect() { [native code] },getClientRects: function getClientRects() { [native code] },getElementsByClassName: function getElementsByClassName() { [native code] },getElementsByTagName: function getElementsByTagName() { [native code] },getElementsByTagNameNS: function getElementsByTagNameNS() { [native code] },getRootNode: function getRootNode() { [native code] },hasAttribute: function hasAttribute() { [native code] },hasAttributeNS: function hasAttributeNS() { [native code] },hasAttributes: function hasAttributes() { [native code] },hasChildNodes: function hasChildNodes() { [native code] },hasPointerCapture: function hasPointerCapture() { [native code] },hidden: false,id: "someElement",innerHTML: "Random Value 29.915196465590597",innerText: "Random Value 29.915196465590597",inputMode: "",insertAdjacentElement: function insertAdjacentElement() { [native code] },insertAdjacentHTML: function insertAdjacentHTML() { [native code] },insertAdjacentText: function insertAdjacentText() { [native code] },insertBefore: function insertBefore() { [native code] },isConnected: true,isContentEditable: false,isDefaultNamespace: function isDefaultNamespace() { [native code] },isEqualNode: function isEqualNode() { [native code] },isSameNode: function isSameNode() { [native code] },lang: "",lastChild: [circular object Text],lastElementChild: null,localName: "p",lookupNamespaceURI: function lookupNamespaceURI() { [native code] },lookupPrefix: function lookupPrefix() { [native code] },matches: function matches() { [native code] },namespaceURI: "http://www.w3.org/1999/xhtml",nextElementSibling: [object HTMLButtonElement] { ... },nextSibling: [object Text] { ... },nodeName: "P",nodeType: 1,nodeValue: null,nonce: "",normalize: function normalize() { [native code] },NOTATION_NODE: 12,offsetHeight: 18,offsetLeft: 8,offsetParent: [object HTMLBodyElement] { ... },offsetTop: 16,offsetWidth: 824,onabort: null,onanimationend: null,onanimationiteration: null,onanimationstart: null,onauxclick: null,onbeforecopy: null,onbeforecut: null,onbeforepaste: null,onbeforexrselect: null,onblur: null,oncancel: null,oncanplay: null,oncanplaythrough: null,onchange: null,onclick: null,onclose: null,oncontextmenu: null,oncopy: null,oncuechange: null,oncut: null,ondblclick: null,ondrag: null,ondragend: null,ondragenter: null,ondragleave: null,ondragover: null,ondragstart: null,ondrop: null,ondurationchange: null,onemptied: null,onended: null,onerror: null,onfocus: null,onformdata: null,onfullscreenchange: null,onfullscreenerror: null,ongotpointercapture: null,oninput: null,oninvalid: null,onkeydown: null,onkeypress: null,onkeyup: null,onload: null,onloadeddata: null,onloadedMetadata: null,onloadstart: null,onlostpointercapture: null,onmousedown: null,onmouseenter: null,onmouseleave: null,onmousemove: null,onmouSEOut: null,onmouSEOver: null,onmouseup: null,onmousewheel: null,onpaste: null,onpause: null,onplay: null,onplaying: null,onpointercancel: null,onpointerdown: null,onpointerenter: null,onpointerleave: null,onpointermove: null,onpointerout: null,onpointerover: null,onpointerrawupdate: null,onpointerup: null,onprogress: null,onratechange: null,onreset: null,onresize: null,onscroll: null,onsearch: null,onseeked: null,onseeking: null,onselect: null,onselectionchange: null,onselectstart: null,onstalled: null,onsubmit: null,onsuspend: null,ontimeupdate: null,ontoggle: null,ontransitioncancel: null,ontransitionend: null,ontransitionrun: null,ontransitionstart: null,onvolumechange: null,onwaiting: null,onwebkitanimationend: null,onwebkitanimationiteration: null,onwebkitanimationstart: null,onwebkitfullscreenchange: null,onwebkitfullscreenerror: null,onwebkittransitionend: null,onwheel: null,outerHTML: "<p id=\"someElement\">Random Value 29.915196465590597</p>",outerText: "Random Value 29.915196465590597",ownerDocument: [object HTMLDocument] { ... },parentElement: [circular object HTMLBodyElement] :
<body style="">
        <p id="someElement">Random Value 29.915196465590597</p>
    <button id="theButton">
      Update
    </button>
    
        <script type="text/javascript">//<![CDATA[
    
    
    function callback(mutationList,observer) {
      mutationList.forEach( (mutation) => {
            console.log(mutation,JSON.stringify(mutation))
        switch(mutation.type) {
          case 'childList':
            /* One or more children have been added to and/or removed
               from the tree.
               (See mutation.addednodes and mutation.removednodes.) */
            break;
          case 'attributes':
            /* An attribute value changed on the element in
               mutation.target.
               The attribute name is in mutation.attributeName,and
               its prevIoUs value is in mutation.oldValue. */
            break;
        }
      });
    }
    
    const targetNode = document.querySelector("#someElement");
    const observerOptions = {
      childList: true,attributes: true,// Omit (or set to false) to observe only changes to the parent node
      subtree: true
    }
    
    const observer = new MutationObserver(callback);
    observer.observe(targetNode,observerOptions);
    
    document.querySelector('#theButton').onclick = function() {
        targetNode.innerText = 'Random Value ' + Math.random()*100;
    }
    
    
      //]]></script>
    
      <script>
        // tell the embed parent frame the height of the content
        if (window.parent && window.parent.parent){
          window.parent.parent.postMessage(["resultsFrame",{
            height: document.body.getBoundingClientRect().height,slug: ""
          }],"*")
        }
    
        // always overwrite window.name,in case users try to set it manually
        window.name = "result"
      </script>
    
        <script>
          let allLines = []
    
          window.addEventListener("message",(message) => {
            if (message.data.console){
              let insert = document.querySelector("#insert")
              allLines.push(message.data.console.payload)
              insert.innerHTML = allLines.join(";\r")
    
              let result = eval.call(null,message.data.console.payload)
              if (result !== undefined){
                console.log(result)
              }
            }
          })
        </script>
    
    
    
    </body>,parentNode: [circular object HTMLBodyElement] :
<body style="">
        <p id="someElement">Random Value 29.915196465590597</p>
    <button id="theButton">
      Update
    </button>
    
        <script type="text/javascript">//<![CDATA[
    
    
    function callback(mutationList,part: [object DOMTokenList] { ... },prefix: null,prepend: function prepend() { [native code] },prevIoUsElementSibling: null,prevIoUsSibling: [object Text] { ... },PROCESSING_INSTRUCTION_NODE: 7,querySelector: function querySelector() { [native code] },querySelectorAll: function querySelectorAll() { [native code] },releasePointerCapture: function releasePointerCapture() { [native code] },remove: function remove() { [native code] },removeAttribute: function removeAttribute() { [native code] },removeAttributeNode: function removeAttributeNode() { [native code] },removeAttributeNS: function removeAttributeNS() { [native code] },removeChild: function removeChild() { [native code] },removeEventListener: function removeEventListener() { [native code] },replaceChild: function replaceChild() { [native code] },replaceChildren: function replaceChildren() { [native code] },replaceWith: function replaceWith() { [native code] },requestFullscreen: function requestFullscreen() { [native code] },requestPointerLock: function requestPointerLock() { [native code] },scroll: function scroll() { [native code] },scrollBy: function scrollBy() { [native code] },scrollHeight: 18,scrollIntoView: function scrollIntoView() { [native code] },scrollIntoViewIfNeeded: function scrollIntoViewIfNeeded() { [native code] },scrollLeft: 0,scrollTo: function scrollTo() { [native code] },scrollTop: 0,scrollWidth: 824,setAttribute: function setAttribute() { [native code] },setAttributeNode: function setAttributeNode() { [native code] },setAttributeNodeNS: function setAttributeNodeNS() { [native code] },setAttributeNS: function setAttributeNS() { [native code] },setPointerCapture: function setPointerCapture() { [native code] },shadowRoot: null,slot: "",spellcheck: true,style: [object CSsstyleDeclaration] { ... },tabIndex: -1,tagName: "P",TEXT_NODE: 3,textContent: "Random Value 29.915196465590597",title: "",toggleAttribute: function toggleAttribute() { [native code] },translate: true,webkitMatchesSelector: function webkitMatchesSelector() { [native code] },webkitRequestFullScreen: function webkitRequestFullScreen() { [native code] },webkitRequestFullscreen: function webkitRequestFullscreen() { [native code] }
  },type: "childList"
}

function callback(mutationList,observer) {
  mutationList.forEach( (mutation) => {
        console.log(mutation,JSON.stringify(mutation))
    switch(mutation.type) {
      case 'childList':
        /* One or more children have been added to and/or removed
           from the tree.
           (See mutation.addednodes and mutation.removednodes.) */
        break;
      case 'attributes':
        /* An attribute value changed on the element in
           mutation.target.
           The attribute name is in mutation.attributeName,and
           its prevIoUs value is in mutation.oldValue. */
        break;
    }
  });
}

const targetNode = document.querySelector("#someElement");
const observerOptions = {
  childList: true,// Omit (or set to false) to observe only changes to the parent node
  subtree: true
}

const observer = new MutationObserver(callback);
observer.observe(targetNode,observerOptions);

document.querySelector('#theButton').onclick = function() {
    targetNode.innerText = 'Random Value ' + Math.random()*100;
}
<p id="someElement">
Some Value
</p>
<button id="theButton">
  Update
</button>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)