简体   繁体   中英

Making a Chrome extension for a site that uses React. How to persist changes after re-rendering?

I want my extension to add elements to a page. But the site uses React which means every time there's a change the page is re-rendered but without the elements that I added.

I'm only passingly familiar with React from some tutorial apps I built a long time ago.

I implemented @wOxxOm's comment to use MutationObserver and it worked very well.

  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);
  }

That being said someone suggested adding the content above the React node (ie the body ) and just positioning the added content absolutely relative to the window. And as this will actually solve a separate problem I was having on some pages of a site I'll probably do that. Also, it's far simpler.

But I thought this was still an interesting solution to a rare problem so I wanted to post it as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM