Refresh iFrame (Cache Issue) - javascript

We are getting a weird issue on which we are not sure what exactly cause it. Let me elaborate the issue. Suppose, we have two different html pages a.html and b.html. And a little script written in index.html:
<html>
<head>
<script>
function reloadFrame(iframe, src) {
iframe.src = src;
}
</script>
</head>
<body>
<form>
<iframe id="myFrame"></iframe>
<input type="button" value="Load a.html" onclick="reloadFrame(document.getElementById('myFrame'), 'a.html')">
<input type="button" value="Load b.html" onclick="reloadFrame(document.getElementById('myFrame'), 'b.html')">
</form>
</body>
</html>
A server component is continuously updating both files a.html and b.html. The problem is the content of both files are successfully updating on the server side. If we open we can see the updated changes but client getting the older content which doesn't show the updated changes.
Any idea?

Add this in a.html and b.html
<head>
<meta http-Equiv="Cache-Control" Content="no-cache" />
<meta http-Equiv="Pragma" Content="no-cache" />
<meta http-Equiv="Expires" Content="0" />
</head>
To force no cache checks

If you can add server-side instructions to those HTML files, you could send the appropriate headers to prevent caching:
Making sure a web page is not cached, across all browsers (I think the consensus is that the 2nd answer is best, not the accepted one)
Simone's answer already deals with Meta tags.
A cheap quick trick is to add a random number as a GET parameter:
page_1.html?time=102398405820
if this changes on every request (e.g. using the current time), reloading wil get forced every time, too.

Try something like the following:
<script>
var frameElement = document.getElementById("frame-id");
frameElement.contentWindow.location.href = frameElement.src;
</script>
This will force the iframe to be reloaded even if it was cached by the browser

I want to put Vishwas comment as a separate answer, extending
Pekka’s answer
//ensure iframe is not cached
function reloadIframe(iframeId) {
var iframe = document.getElementById(iframeId);
var d = new Date();
if (iframe) {
iframe.src = iframe.src + '?ver=' + d.getTime();
//alternatively frameElement.contentWindow.location.href = frameElement.src; //This will force the iframe to be reloaded even if it was cached by the browser
}
}
reloadIframe('session_storage_check');

Homero Barbosa's Solution worked like a charm. In my case, I had a varying number of iframes on the page, so I did the following:
$('.some_selector').each(function () {
var $randid = Math.floor(Math.random() * 101);
$(this).attr({'id': 'goinOnaSafari-' + $randid});
var $frame = document.getElementById('goinOnaSafari-' + $randid);
$frame.contentWindow.location.href = $frame.src;
});

I could not get the HTML to work.
<head>
<meta http-Equiv="Cache-Control" Content="no-cache" />
<meta http-Equiv="Pragma" Content="no-cache" />
<meta http-Equiv="Expires" Content="0" />
</head>
For development in chrome I checked the console Network tab and found where the iframe is loaded.
I confirmed that it was loaded with a 304 response wich means it loads from cache.
Right click -> clear browser cache.
Will not work in production, but at least helps with development.

For one possible solution to this, pass a "cache parameter" to your calls to a.html and b.html. For example
HTML
<input type="button" value="Load a.html" onclick="cacheSafeReload('a.html');">
Javascript
function cacheSafeReload(urlBase) {
var cacheParamValue = (new Date()).getTime();
var url = urlBase + "?cache=" + cacheParamValue;
reloadFrame(document.getElementById('myFrame'), url);
}

Related

How can I change my code to be able to calculate different urls instead of the current page

I'm trying to calculate the load time and page size of different URLs/Pages similar to the developer tools performance tab but in javascript. But the current code only calculates its current page instead of a different URL. Is there any way for me to do this because with my research I have no luck.
<html>
<head>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<script type="text/javascript">
var start = new Date().getTime();
function onLoad() {
var now = new Date().getTime();
var latency = now - start;
alert("page loading time: " + latency+"\n"+"Start time:"+start+"\n"+"End time:"+now);
alert("Load_size:"+document.getElementsByTagName("html")[0].outerHTML.length + "KB");
}
</script>
</head>
<body onload="onLoad()">
<!- Main page body goes from here. -->
</body>
</html>
It will not be possible to read the runtime parameters of a page outside the page your javascript is running on.
Part of the security model is to avoid being able to inspect the runtime of other pages. This is called the "sandbox". You'll need to build a plugin that breaks the sandbox to inspect the domLoad / domReady and other performance events.
Good news though, you probably have one built in! The console for modern browsers shows all those events in the timeline tab.
If you're trying to make a service that attempts to evaluate the runtime of other pages, you'll need to load those in a virtual web browser on the server and interpret the results using selenium or something similar.
You can try this to calculate the load time of a page:
<script type="text/javascript">
$(document).ready(function() {
console.log("Time until DOMready: ", Date.now()-timerStart);
});
$(window).load(function() {
console.log("Time until everything loaded: ", Date.now()-timerStart);
});
</script>
edit: this will only work on pages where this JS code will run, so if you cant insert code onto the page you wont be able to run it.

How to automatically refresh external data loaded into Javascript variables in HTML?

I have digital information written as Javascript variables by PHP into a .txt-File. This information gets changed by a user at a different interval.
var ISTUHSXDATE8 = '21.1.2018';
var ISTUHSXTIME8 = '20:11';
var ISTUHSXROT8 = 0;
var ISTUHSXGELB8 = 0;
var ISTUHSXGRUEN8 = 1;
var ISTUHSXAUSLASTUNG8 = '0%';
To show actual information in the HTML body, it´s necessary to make the HTML document load the latest version of .txt from server. [At the moment handmade by push the button and in webprojekt by setInterval() automatically]
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv='cache-control' content='no-cache'>
<script type="text/javascript" id="id_of_java_var"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var dsts = new Date();
document.getElementById("id_of_java_var").src =
"https://www.juh-technik.de/StreifenstatusEA1.txt?time" + dsts.getTime();
}
</script>
</body>
</html>
With this code I can load latest version from the server for several .gif/.jpg/.html files by pushing the refresh button. The Problem is, this don´t works with .txt-files.
So my question is, how to refresh src of following line without page reload.
<script src="https://www.juh-technik.de/StreifenstatusEA1.txt" type="text/javascript" id="id_of_java_var"></script>
Thanks for your help :-)

HTML5 video canPlay event not working second time

I am working on some site in php. The pages are loaded through ajax. One of the pages has HTML5 video. Before the video can play I show a loader on top of it. Once it goes in the canPlay event I remove the loader div. But the problem is, when I come on this page for the first time it works fine and goes into the canplay function. But if I go to the next page and come back it doesn't go into the canplay function at all show the loading image does not get removed.
Can anyone please help me and tell me a solution for this. Thanks in advance.
var videoObj = document.getElementById('video');
jQuery('.moduleBody').append('<div class="videoLoader" id="videoLoadingDiv"><img src="images/loader.gif" /></div>');
jQuery(videoObj).on('canplay', function(){
jQuery('#videoLoadingDiv').remove();
});
Regards,
Neha
I found out what the issue was. The video was getting cached so on refresh also it used to remain cached in the browser. So what I have done is, I am passing a random value as a parameter in the src of the 'video' tag. So now the video does not get cached in the browser and it goes inside the canPlay() function.
Anyways thanks for your answers.
Regards,
Neha
There is a lot of code missing but I would put your script in side this
$( document ).ready(function() {
console.log( "ready!" );
});
also consider using .hide(); rather than .remove();
The use the Use the $(window).unload(function(){}); method
Could not hurt to add this then
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Changing the content of meta refresh does not change refreshing time

I have a meta http-equiv="refresh" inside the <head>.
<head>
<meta name="mymeta" http-equiv="refresh" content="2" id="myMeta">
</head>
Using Javascript, I'm trying to change the content attribute of this meta tag.
var myMeta = document.getElementById("myMeta");
myMeta.content="10";
When I display the content via document.write(myMeta.content);, I get the changed value which is 10, however, the meta tag will keep refreshing each 2 seconds.
I have tested this both in Firefox and Opera.
FULL PAGE
<!DOCTYPE html>
<html>
<head>
<meta name="mymeta" http-equiv="refresh" content="2" id="myMeta">
<script>
var myMeta=document.getElementById("myMeta");
myMeta.content="10";
document.write(myMeta.content);
</script>
</head>
<body>
</body>
</html>
This happens because the browser immediately process the <meta> tag when it is present onload.
See DEMO.
When the document is being loaded, the browser sees and processes the following:
<meta name="mymeta" http-equiv="refresh" content="2" id="myMeta"/>
Even though you try to change its content from 2 to 10, that 2 second refresh is already acknowledged and the browser waits for 2 seconds before it refreshes the page. The 10-second refresh that is injected by JavaScript actually works*, although the page has been refreshed by the time it reaches 2 seconds and nothing seems to happen. This process is then repeated again and again.
Try the opposite and see what happens.
*This only works on Safari and Chrome. Firefox and Opera does not support the modification of meta refresh through JavaScript.
The getElementsByTagName method returns a NodeList so you need to specify an index to correctly access the element:
var myMeta = document.getElementsByTagName("meta")[0];
As someone mentioned this will probably still not work as the meta tag will need to be re-appended to have the desired effect.
Since you're using JavaScript you can just use setTimeout to achieve the same behavior
setTimeout(function() {
location.reload();
},2000); // reload page after 2 seconds

How to open a native iOS app from a web app

Summary I have an app with a correctly functioning URL scheme that I'd like to launch from a web app stored on the home screen, and the normal JavaScript redirect methods don't seem to work.
Details I'm trying to create an iOS web app, to be opened in full-screen mode from a link saved on the Home Screen. The web app needs to open a specific native app. I have already registered the url scheme for the native app, and verified that it works correctly - I can open the native app by typing the scheme directly into my Safari address bar, for instance. I can also open it from other applications using the +openURL: method of UIApplication. I would like to also open it with certain arguments from a native web app that can be added to the home screen.
What I'm trying to do is use JavaScript like so inside the native app:
window.location = "myapp://myparam";
When using this code inside the web app I get an alert saying:
"Cannot Open myWebAppName - myWebAppName could not be opened. The
error was "This URL can't be shown".".
This same javascript when executed within Safari works correctly. I get the same result using window.location.replace("myapp://myparam").
The html for the web app is:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
<meta name="generator" content="TextMate http://macromates.com/">
<meta name="author" content="Carl Veazey">
<!-- Date: 2012-04-19 -->
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta names="apple-mobile-web-app-status-bar-style" content="black-translucent" />
</head>
<body>
<script type="text/javascript" charset="utf-8">
if (window.navigator.userAgent.indexOf('iPhone') != -1) {
if (window.navigator.standalone == true) {
window.location = "myapp://myparam";
} else {
document.write("please save this to your home screen");
};} else {
alert("Not iPhone!");
document.location.href = 'please-open-from-an-iphone.html';
};
</script>
</body>
</html>
What am I doing wrong here? I'm pretty inexperienced with javascript and mobile web so I suspect I'm just missing something obvious.
Your code works if its in mobile safari but NOT if its from a bookmark on the iOS desktop. Never tried it that way before, but thats the issue. If i just set your JS to
<script type="text/javascript" charset="utf-8">
window.location = "myapp://myparam";
</script>
It works in browser, but when bookmarked it fails. It might have to do something with how the url is loaded when its bookmarked since there is no chrome? My guess is that apple doesn't want booked mark pages to access local apps. Also, I've noticed that if I bookmark a locally hosted page, that works in mobile safari, I can't get it to load via bookmark. Its really odd....
Best recommendation I have for you is to make it
<meta name="apple-mobile-web-app-capable" />
instead of
<meta name="apple-mobile-web-app-capable" content="yes" />
This way it will be on the home screen, but will unfortunately load with the chrome. Thats the only solution I can think of.
If you need to open an iOS application if it is installed and also want to preserve your page's functionality, the location.href = 'myapp://?params=...'; won't help since if myapp:// is not registered, the redirect leads user to unreachable destination.
The safest bet seems to be in using an iframe. The following code will open an iOS app if it is installed and will not cause a failure if it is not (though it may alert a user that the page could not be reached if the app is not installed):
var frame = document.createElement('iframe');
frame.src = 'myapp://?params=...';
frame.style.display = 'none';
document.body.appendChild(frame);
// the following is optional, just to avoid an unnecessary iframe on the page
setTimeout(function() { document.body.removeChild(frame); }, 4);
Try like this:
The index page
<html><head></head><body>
<?php
$app_url = urlencode('YourApp://profile/blabla');
$full_url = urlencode('http://yoursite.com/profile/bla');
?>
<iframe src="receiver.php?mylink1=<?php echo $app_url;?>" width="1px" height="1px" scrolling="no" frameborder="0"></iframe>
<iframe src="receiver.php?mylink2=<?php echo $full_url;?>" width="1px" height="1px" scrolling="no" frameborder="0"></iframe>
</body>
</html>
the receiver.php page:
<?php if ($first == $_GET['mylink1'])) { ?>
<script type="text/javascript">
self.window.location = "<?php echo $first;?>";
</script>
<?php } if ($second == $_GET['mylink2'])) { ?>
<script type="text/javascript">
window.parent.location.href = "<?php echo $second ;?>";
//window.top.location.href=theLocation;
//window.top.location.replace(theLocation);
</script>
<?php } ?>
To provide an update, iOS14 Beta7 doesn't appear to be opening any local apps via their registered x-callback URLs. 👎
<?php
// Detect device type
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
// Redirect if iPod/iPhone
if( $iPod || $iPhone ){
header('Location:http://example.com');
}
?>
The above will redirect the browser to the inputted URL (http://example.com/) if the device is an iPod or iPhone. Add the script to the top of your web app, make sure you save it as a .php file rather than .html.
Source:
http://www.schiffner.com/programming-php-classes/php-mobile-device-detection/

Categories