Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Entire Page Including Head Using Javascript

I have a Javascript function that is passed a string. The string that it is passed is an entire webpage, including the header. I need the Javascript to replace the entire current page, head and all with the new content.

Consider the following HTML file:

<html>   <head>     <script language="Javascript">       <!--       var newContent='<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html>';       function ReplaceContent(NC) {         document.body.innerHTML=NC;       }       function Hi() {         alert("Hello World");         ReplaceContent(newContent);       }       -->     </script>   </head>   <body onload="Hi();">     Original Content   </body> </html> 

In this case, the passed string is:

<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html> 

But of course, since the "ReplaceContent" function is only replacing the body, but not the header, I never get the "Goodbye World" alert.

Ignoring "why I would want to do this", How can I dynamically replace the entire page, including the header, and javascript functions?

Please remember the "source" html ('newContent' above) exists only as a string, it does not exist on a server anywhere, so I cannot just redirect to it.

What changes I make to "ReplaceContent" above to cause the "Goodbye World" alert to appear once the content is replaced? Please keep in mind I cannot know in advance the value of the newContent variable!!

like image 417
Joshua Avatar asked Nov 27 '10 16:11

Joshua


People also ask

Can you replace HTML with JavaScript?

One very useful ability provided by JavaScript is the ability to replace the content of elements in an existing HTML document that was previously displayed, even empty elements. There are many reasons that a web designer may choose to take advantage of this ability but providing interactive pages is a likely goal.

How do I clear a page in JavaScript?

If by "clear" you mean to remove existing content of page then here is JS way: document. body. innerHTML=""; it'll overwrite everything from page.


1 Answers

Use document.write.

<html>   <head>     <script language="Javascript">       <!--       var newContent='<html><head><script language="Javascript">function Hi() {alert("Goodbye World");}</script></head><body onload="Hi();">New Content</body></html>';       function ReplaceContent(NC) {         document.open();         document.write(NC);         document.close();       }       function Hi() {         ReplaceContent(newContent);       }       -->     </script>   </head>   <body>     Original Content     <a href="javascript:Hi()">Replace</a>   </body> </html> 
like image 168
Dark Falcon Avatar answered Oct 08 '22 11:10

Dark Falcon