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?
innerHTMLcreates no additional risk. If the article is added or editedable by a user, any risk arises at that point, so if you're comfortable with your source, you should be comfortable using it elsewere. MDN notes a new featureElement.setHTML()for insertions from dubious sources developer.mozilla.org/en-US/docs/Web/API/Element/setHTML but your source sounds safe.