Padax / w-components

JavaScript library based on Web Components.
MIT License
22 stars 2 forks source link

<script> is executed in Code #131

Closed nizniz187 closed 2 years ago

nizniz187 commented 2 years ago

Because the code inside Code component is not wrapped in <code> tags, causing it being parsed and executed on DOM content loaded.

nizniz187 commented 2 years ago

This issue is more complex than I thought because of multiple misconceptions.

1. I thought the native HTML tag <code> and <pre> handle HTML tags well. So we may need to force user to wrap content into any of these tags. It turned out that neither of them handle any HTML tag escape at all. They simply presume there is no HTML tag inside, otherwise it should be taken care by the developers.

2. I tried to escape HTML tags like '<', '>' and '&', but the highlighted outcome preserved all the escaped format. Actually, highlight.js has already taken the code content as text. So the escaped tags are not detected as HTML code anymore. (See https://github.com/highlightjs/highlight.js/issues/2886)

3. Then what we need to handle with is only the unintentional JS triggering. At last, I changed the inner HTML of Code after content load, which brought out MutationObserver implementation to handle later content change.

cwpeng commented 2 years ago

Let us clarify the solution. It means there is empty inside w-code component at first, and then, we add JavaScript code by innerHTML, triggering MutationObserver to do something which will not execute JavaScript code.

nizniz187 commented 2 years ago

Yes. For the MutationObserver triggering part, it simply triggers code parsing. It was surprising for me that delayed innerHTML injection didn't trigger JS code running... but that's how it worked. See commit b8ae1fd for more details.

nizniz187 commented 2 years ago

@cwpeng Please help review and close this issue if it looks good for you.

nizniz187 commented 2 years ago

If we both agree this is the only way to parse HTML tags normally, then we'll need to add specific documentation for this workaround.