Inserting scripts into a page using innerHTML to a
The HTML provided in the sample code demonstrates the attempted execution of a script within a
To address this issue, we present a method that recursively replaces all non-executable scripts with executable ones. This method, known as nodeScriptReplace, traverses the DOM tree and identifies script elements. If a non-executable script is encountered, it clones the script, assigns it executable content, and replaces the original script element, enabling it to be executed.
Additionally, the nodeScriptClone function creates an executable script element by extracting the innerHTML of the non-executable script and setting its attributes. These attributes are transferred to the new executable script, ensuring proper behavior.
The nodeScriptIs function checks if a given node is a script element by examining its tag name.
To execute the script and display the "hi" alert, simply call nodeScriptReplace on the page's root element. The code snippet below demonstrates this:
This method provides a robust mechanism for executing scripts added to a page using innerHTML, ensuring their intended functionality.
The above is the detailed content of Why Don't Scripts Added via innerHTML Always Execute, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!