Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  3] [ 7]  / answers: 1 / hits: 59676  / 14 Years ago, sat, november 27, 2010, 12:00:00

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!!


More From » html

 Answers
120

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>

[#94819] Thursday, November 25, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayden

Total Points: 108
Total Questions: 109
Total Answers: 107

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;