代码之家  ›  专栏  ›  技术社区  ›  MCB

为使用react的站点生成chrome扩展。如何在重新渲染后保持更改?

  •  0
  • MCB  · 技术社区  · 6 年前

    我希望我的扩展名向页面添加元素。但网站使用 React 这意味着每次发生更改时,都会重新呈现页面,但不包含我添加的元素。

    我只是被动地熟悉一些我很久以前构建的教程应用程序的反应。

    1 回复  |  直到 6 年前
        1
  •  0
  •   MCB    6 年前

    我执行了@woxxom的评论 MutationObserver 而且效果很好。

      static placeAndObserveMutations (insertionBoxSelector) {
        let placer = new Placement ();
        placer.place(insertionBoxSelector);
        placer.observeMutations(insertionBoxSelector);
    
      }
    
      place (insertionBoxSelector) {
        let box = $(insertionBoxSelector)
        this.insertionBox = box; //insertionBox is the element that the content
        // will be appended to
        this.addedBox = EnterBox.addInfo(box); //addedBox is the content
    // Worth noting that at this point it's fairly empty. It'll get filled by
    // async ajax calls while this is running. And all that will still be there
    // when it's added back in the callback later.
      }
    
      observeMutations(insertionBoxSelector) {
        let observer = new MutationObserver (this.replaceBox.bind(this));
    // this.insertionBox is a jQuery object and I assume `observe` doesn't accept that
        let insertionBox = document.querySelector(insertionBoxSelector);
        observer.observe(title, {attributes: true});
      }
    
      replaceBox () {
        this.insertionBox.append(this.addedBox);
        _position (this.addedBox);
      }
    

    据说有人建议将内容添加到 React 节点(即 body )只需将添加的内容绝对相对于窗口进行定位。因为这实际上可以解决我在某个网站的某些页面上遇到的一个单独的问题,所以我可能会这样做。而且,这要简单得多。

    但我认为这仍然是一个有趣的解决方案,一个罕见的问题,所以我想张贴它以及。