I am using the html-react-parser
library to convert a string representing an HTML snippet into a React component. The string contains a component and a with an onload attribute. Here’s an example of the HTML string:
const html = `
<div id="component">...</div>
<script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;
The HTML string is processed and converted into a React component using html-react-parser. The approach involves parsing the string and replacing local sources with sources hosted on a CDN. To achieve this, I use the replace option from html-react-parser. Here is my current implementation:
import parse from 'html-react-parser';
const html = `
<div id="component">...</div>
<script src="/component/index.js" onload="initComponent(94239483, 4)"></script>
`;
const parsedHTML = parse(html, {
replace(domNode) {
if (isAReplaceableScript(domNode, 'true')) {
return replaceLocalScript(domNode, customization.javascript);
}
},
});
const replaceLocalScript = (domNode, files) => {
const localSource = domNode.attribs.src;
const cdnSource = files[localSource];
const { attribs } = domNode;
const onLoad = new Function('alert("It is working")');
const updatedAttribs = { ...attribs, src: cdnSource };
return cdnSource ? <script {...updatedAttribs} onLoad={onLoad} defer /> : <></>;
};
The updated appears correctly in the browser’s HTML with the src attribute pointing to the CDN URL, but the onLoad event does not trigger. When inspecting the script in the browser, the onLoad property does not appear.
onLoad
event to trigger?html-react-parser
is ignoring the onLoad
event for <script>
tags?