I have got two html
files, say page1.html
and page2.html
. In both files I have an article
element. Now, on page1.html
I would like to replace the content of the article
element with that of page2.html
using JavaScript (I don't want to use jQuery).
Currently, my solution is the following: When page1.html
is loaded, I use the fetch
method to get the content of page2.html
's article
element. Then, when the user clicks a button, I call
article.innerHTML = newContent;
This does work fine so far, but recently I've read that innerHTML
shouldn't be used to prevent XSS attacks. Obviously, I cannot set the property article.textContent
since I've got "real" html
code in my articles that I want to be interpreted as such. Another solution I could think of is to include the html
code in the script file as a string. The downside of this method would be that I would have to change both page2.html
and the script file, whenever I want to change the article.
Is there a recommended way to achieve what I want to do? Also, all the examples of XSS attacks I've read about seem to indicate that my specific use of innerHTML
doesn't allow XSS attacks (since I fetch the code from a site which I control myself), but I don't just want to be like "I can't think of an XSS attack, so there'll never be one". Any insights about the danger of XSS attacks in this context would also be appreciated.
Thank you in advance!
CodePudding user response:
In case you have control over the content of this page2.html
i.e. either you have a static or dynamic data which is not generated by the visitors visiting your webpages, then there is won't be any issue of XSS attack. In such cases you can confidently use innerHtml
method.
But, in case the content of the page2.html
contains the data from visitors (such as comments, posts, etc.) then only there is a chance of XSS attack. XSS attack is nothing but when your user put some JavaScript code for their advantage.
E.g. In case your page2.html contains comments, I can post comment like Hello world! <script> alert("You have been hacked, transfer money to this bank to save your computer") </script>
. Or I can attach link to another vulnerable script which steal your user's data like cookie data.
For such use cases, please do not use innerHtml
directly. The safe solution is either use textContent
or sanitize your visitor's data (like the comment mentioned above) (Ref: https://remarkablemark.org/blog/2019/11/29/javascript-sanitize-html/)
CodePudding user response:
try the following code here you have to call the .text() method in fetch response to get the actual HTML and insert it using Element.innerHTML
fetch('DataPage.html') .then((res) => res.text()) //here you have to change the response into html text .then(res => {document.querySelector("#target").innerHTML = res;})