I'm creating a tool that takes an URL, fetches the document, modifies its contents and sends it to the browser. I add some tags to the HTML. I have two questions:

1) I want the user to feel as little as possible that they're not on the original page. I want the links to work, the design to stay the same, the original scripts to work etc. So far I only thought about modifying relative links. But there may be other things that may get broken by the wrapping. So, is there perhaps a library / generic tool for wrapping web pages that does all this for me?

2) I want to add spans and hyperlinks into the original HTML. However, these aren't allowed everywhere in every document type and I'd love to keep the document valid if it was valid before. So, is there a way to check if the document type allows me to create an element in a particular place?