简体   繁体   中英

How to capture third-party JS library DOM changes using React?

I'm appending a third-party JavaScript library that is required by payment gateway I'm using. This library adds hidden inputs to form (with errors, code values, etc.) after submit. How can I capture HTML DOM changes caused by this library?

I tried to use document.getElementsByName on form submit, but it doesn't work. It seems that the third-party library HTML DOM change is executed after my onClick function and I don't know what to do with that.

<input type="hidden" name="crazy_payment_gateway_error_name" value="2" />

For that you can use DOM Mutation observer. It let you watch and inspect changed to your elements.

// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

Your callback will get into about changes to the DOM. Source code and more info on MDN:

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

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