This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 5 years ago.
I need some help with my html code. I need to integrate javascript in it which upon loading checks whether internet is available or not. If active it should perform specific task, else it should show "no internet".
`<html>
<head>
</head>
<body onload="myClickHandler();
startTime()">
<script language="JavaScript">
var t;
document.onclick = myClickHandler;
function myClickHandler() {
clearTimeout(t);
t = setTimeout("location.href='index.html'", 60000);
//for refreshing the page in every 60 sec.
}
</script>
<h1> test </h1>
<script type="text/javascript">
var url = "https://www.google.co.in";
var img = new Image();
img.src = url;
img.onerror = function()
{
// If the server is down, do that.
alert ("no connection");
}
img.onload = function()
{
// If the server is up, do this.
//some task to perform.
return true;
}
</script>
</body>
</html>`
This is what i code, but page is keep on loading after the performance also we need to manually stop the loading.
Use the below code. Thanks to this post .
To know more about navigator.online plz check the below link
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
<!doctype html>
<html>
<head>
<script>
function CheckOnlineStatus(msg) {
var status = document.getElementById("status");
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
var state = document.getElementById("state");
state.innerHTML = condition;
}
function Pageloaded() {
CheckOnlineStatus("load");
document.body.addEventListener("offline", function () {
CheckOnlineStatus("offline")
}, false);
document.body.addEventListener("online", function () {
CheckOnlineStatus("online")
}, false);
}
</script>
<style>
...</style>
</head>
<body onload="Pageloaded()">
<div id="status">
<p id="state">
</p>
</div>
</body>
</html>
Related
I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>
I have a simple webapp that show a button and when a user clicked, it will open a new window that shows a website. What I want to do is when a user clicked the button, it will get the value from my google sheet and open a new window based on that value. Then, the webapp will update the value in the google sheet with a new value.
For example:
if the value in my google sheet is "Google", it will open a window to "www.google.com" and then update the google sheet value to "other website".
I have succesfully made the function for updating the value on google sheet whenever a user clicked the button but I fail in getting the value from the code.gs/google sheet to my Javascript.
Please help.
here is my code.gs:
var url = "url"; //mygooglesheet url
var web = "";
function doGet(e) {
let tmp = HtmlService.createTemplateFromFile("index");
return tmp.evaluate();
}
function setWebsite () {
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("website");
web = ws.getRange(1,1,1,1).getValue();
if (web === "Google") {
ws.getRange(1,1,1,1).setValue("Youtube");
}
else if (web === "Youtube") {
ws.getRange(1,1,1,1).setValue("Facebook");
}
else {
ws.getRange(1,1,1,1).setValue("Google");
}
}
function getWebsite() {
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("website");
var web = ws.getRange(1,1,1,1).getValue();
return web;
}
my index.html:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Please Click Below</h1>
<!-- <h2><?=web?>:</h2> -->
<button id = "btn" type="submit" >Open Window</button>
<script>
document.getElementById("btn").addEventListener("click", doStuff);
var web = "";
function doStuff() {
google.script.run.getWebsite(); //dont know for sure if this is needed or not
google.script.run.setWebsite();
web = <?=web?>; //dont know for sure if this is needed or not
if (web === "Google") {
window.open("https://www.google.com/");
}
else if (web === "Youtube") {
window.open("https://www.youtube.com/");
}
else {
window.open("https://www.facebook.com/");
}
}
</script>
</body>
</html>
Right now, my webapp only open a new window to "facebook.com" and update to the next value in the code. I tried "google.script.run.withSuccessHandler(onSuccess).getWebsite()" but not successful to get the variable value from the code.gs, please help.
Thank you.
Issue:
You want to open a new tab with the URL returned by getWebsite() when the button is clicked.
Solution:
In order to handle data returned by a server-side function called by google.script.run, use the success handler. The function called by this handler will be passed the value returned by the server-side function (getWebsite()) as a parameter.
Code sample:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Please Click Below</h1>
<button id = "btn" type="submit" >Open Window</button>
<script>
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
google.script.run.withSuccessHandler(openWebsite).getWebsite();
}
function openWebsite(web) {
if (web === "Google") {
window.open("https://www.google.com/");
} else if (web === "Youtube") {
window.open("https://www.youtube.com/");
} else {
window.open("https://www.facebook.com/");
}
}
</script>
</body>
</html>
Note:
If the data returned by getWebsite() is supposed to remain static between the moment in which the page first loads and when the button is clicked, you could also use the approach mentioned by Mike Steelson, using template scriplets.
In html, in script section, write
<? var web = getWebsite(); ?>
and erase google.script.run.getWebsite();
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
I have a Raspberry PI with a button attached to it.
I run a Python script on it to detect when the button is pressed.
When the button is pressed, it increment a number in a text file.
I need to display this number on a web page (Apache) and to launch a sound.
For the moment, my python script change the index.html with the value I need and I am using <meta http-equiv="refresh" content="1"> to resfresh the page.
The problem is that I need to know when the number is changing to launch the sound.
Too little information to say something concrete, but here's how I'd get around to it given the main following limitation that the page is not dynamic (no ajax).
General outline:
Put the value from the text file in a identifiable field like
<span id="myNumber">#the number from file goes here </span>
then on load with java script read the value of the field:
(planin JS)
var myNumberValue = document.getElementById('myNumber').innerHTML;
then create a cookie to store the last value on clinets machine:
document.cookie = "lastNumber="+myNumberValue;
To sum it all up: on loading the webpage launch a script that will :
check for a cookie
read a value from the coookie
(http://www.w3schools.com/js/js_cookies.asp)
read a value from the field
if a cookie exists compare the values and if the number
changed play a sound like here:
Playing audio with Javascript?
either way store the value from the field to the cookie for next
website update.
[Edit] Full working solution using local storage or cookies:
<html>
<head>
<META HTTP-EQUIV="refresh" CONTENT="5">
<script type="text/JavaScript">
function myFunction()
{
var numberDisplayed = parseInt(document.getElementById('myNumber').innerHTML);
var numberInCookie = numberDisplayed;
//lets assume that's the only data in the cookie
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(numberDisplayed!=numberInCookie)
{
alert("changed to from "+ numberInCookie+" to " + numberDisplayed);
}
saveNumber(numberDisplayed);
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that's the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>
[Edit 2] as the author of the question hinted he doesn't actually want to use the site refresh here's another option:
lest start a loop that will load a test file from the server as an ajax request. then the data is loaded, parsed, store it loacally as before. and set timer to trigger the refresh again.
One importatnt thing the files need to be available on the same domain / server (see HTTP access control (CORS) for more information)
<html>
<head>
<script type="text/JavaScript">
var externalNumber = 0;
var timer;
function myFunction()
{
// start the readouts:
LoadExternalData();
}
function LoadExternalData()
{
var client = new XMLHttpRequest();
client.open("GET", "http:/myserver/readme.txt");
client.onreadystatechange = function() {
externalNumber = parseInt(responseText);
//store a local copy
var NewestNumber = externalNumber;
var tmpData = readNumber();
if(tmpData!="NaN" && tmpData!= "undefined")
{
numberInCookie = tmpData;
}
if(NewestNumber!=numberInCookie)
{
alert("changed to from current "+ numberInCookie+" to " + NewestNumber);
}
saveNumber(NewestNumber);
timer = setTimeout(LoadExternalData, 1000);
}
client.send();
}
function readNumber()
{
if (typeof(Storage) !== "undefined") {
return localStorage.getItem("lastNumber")
} else {
var cookieData = document.cookie;
//lets assume that is the only data in the cookie
var tmpData = parseInt(cookieData.split("=")[1]);
return tmpData
}
}
function saveNumber(number)
{
if (typeof(Storage) !== "undefined") {
localStorage.setItem("lastNumber", number);
} else {
document.cookie = "lastNumber="+number;
}
}
</script>
</head>
<body onload="myFunction()">
<span id="myNumber">2</span>
</body>
</html>
This problem is only happening in IE (at least 8 and 9). After an element is dynamically added to the DOM, the contents of an embedded iframe are lost when the page is reentered with a BACK/FORWARD key. Just two small HTML files will reproduce the issue.
The first file is iframe.htm:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function mytrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b); /// will work if commented
}
function submitListing() {
mytrace('submitListing()');
var doc = document.getElementById("output_iframe")
.contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//mytrace('submitListing(): out');
}
</script>
</head>
<body>
<div id="trace_output"><br /></div>
<input type="button" onclick="submitListing();" value="Run" /><br />
<iframe id="output_iframe" src=""></iframe>
</body>
</html>
The second file is report.htm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
LINK
</body>
</html>
Steps to recreate the issue (BACK KEY)
Place above content in two files
Browse the iframe.htm file
Press the Run button to load report.htm in the iframe
Click on the LINK link to load a different page
Press the browser BACK button to returned to the "cached" (lmao) page
iframe contents are gone!!!! (only in IE-- safari, chrome, firefox retain the contents)
Also..(FORWARD KEY)
Browse to an arbitrary page (for history, http://www.google.com works)
Load iframe.htm into the same tab
Press the Run button to load report.htm in the iframe
Press the browser BACK button to return to the first page
Press the browser FORWARD button to return to iframe.htm
iframe contents are gone again!!
Now comment out the line:
d.appendChild(b)
That one change allows everything to work in IE. However, my solution needs to make those kinds of DOM manipulations (heavy jQuery/AJAX app) AND be able to restore the iframe across browser BACK/FORWARD actions.
It seems that I will have to remember the contents of the iframe so that I can restore it when the page is accessed with the BACK/FORWARD keys. I'm not thrilled with this because sometimes the iframe content will be quite large and it could chew up a bit of memory and time to make another copy of the embedded document for the restore. I would love to hear some other ideas about how I could approach this. Thanks in advance.
EDIT
The following replacement to iframe.htm will work around the problem with IE. I'm going to rewrite this using jQuery and add some more logic to restore the scroll positions. I had hoped for something more elegant, but this is doing the job.
<!DOCTYPE html>
<html>
<head>
<title>IE iframe bug</title>
<script type="text/javascript">
function myTrace(msg) {
var t = document.createTextNode(msg);
var b = document.createElement('br');
var d = document.getElementById("trace_output")
d.appendChild(t);
d.appendChild(b);
}
var make_backup ="false";
function submitListing() {
make_backup = "true";
myTrace('submitListing()');
var doc = document.getElementById("output_iframe").contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache=' + d.getTime());
//myTrace('submitListing(): out');
}
function iframe_load() {
myTrace("iframe loaded, is_cached=" + document.getElementById("is_cached").value);
if (make_backup == "true") { // only when submitting
var htm, doc;
make_backup = "false"
doc = document.getElementById("output_iframe").contentWindow.document;
htm = doc.documentElement.innerHTML;
document.getElementById("iframe_backup").value = htmlEscape(htm);
}
}
function bodyLoaded() {
var is_cached = document.getElementById("is_cached");
if (is_cached.value == "false") { // initial page load
is_cached.value = "true";
}
else { // BACK or FORWARD, restore DOM where needed
var htm;
htm = htmlUnescape(document.getElementById("iframe_backup").value);
var doc;
doc = document.getElementById("output_iframe").contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
}
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body onload="bodyLoaded();">
<div id="trace_output" style="height: 300px; border-width:1; background-color: Silver"><br></div>
<input id="is_cached" type="hidden" value="false">
<input id="iframe_backup" type="hidden">
<input type="button" onclick="submitListing();" value="Run"><br>
<iframe id="output_iframe" src="" onload="iframe_load();"></iframe>
</body>
</html>
EDIT 2
Rewritten with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>IE iframe workaround2</title>
<script type="text/javascript" src="Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
var make_backup = "false";
$(document).ready(function () {
myTrace('document ready()');
var is_cached = $("#is_cached");
if (is_cached.val() == "false") { // initial page load
is_cached.val("true");
}
else { // BACK or FORWARD, restore DOM where needed
if ($.browser.msie) { // IE loses iframe content; restore
var htm = htmlUnescape($("#iframe_backup").val());
var doc = $("#output_iframe")[0].contentWindow.document;
doc.open();
doc.writeln(htm);
doc.close();
myTrace('iframe contents restored');
}
}
$('#output_iframe').load(function () {
myTrace("iframe_loaded");
if (make_backup == "true") { // only when submitting
make_backup = "false"
if ($.browser.msie) {
var doc = $("#output_iframe")[0].contentWindow.document;
var htm = doc.documentElement.innerHTML;
$("#iframe_backup").val(htmlEscape(htm));
myTrace('iframe contents backed up');
}
}
});
$('#submit_listing').click(function () {
make_backup = "true";
myTrace('submitListing()');
var doc = $("#output_iframe")[0].contentWindow.document;
var d = new Date;
doc.location.replace('report.htm?invalidateCache='+d.getTime());
});
});
function myTrace(msg) {
$('#trace_output').append(msg + '<br>');
}
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/"/g, '"')
.replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
function htmlUnescape(str) {
return String(str).replace(/&/g,'&').replace(/"/g,'"')
.replace(/'/g,"'").replace(/</g,'<').replace(/>/g,'>');
}
</script>
</head>
<body>
<div id="trace_output"
style="height: 300px; border-width:1; background-color: Silver">
<br></div>
<div style="display: block;">
<input id="is_cached" type="text" value="false">
<input id="iframe_backup" type="text" type="hidden"></div>
<input id="submit_listing" type="button" value="Run"><br>
<iframe id="output_iframe" src=""></iframe>
</body>
</html>