I don't know what's wrong with my code, even if I change the content of the target file it still wont refresh the iframe.
<script type="text/javascript">
var page = 'data/apps/<? echo $_SESSION['name']; ?><? echo $_SESSION['last']; ?>App.html', lM;
function checkModified(){
$.get(page, function(a,a,x){
var mod = x.getResponseHeader('last-modified');
if(lM != mod){
lM = mod;
document.getElementById("frame").src += "";
}
}
}
setInterval(checkModified, 5000); // every 5 seconds
</script>
What I want to achieve is when there are changes on the target page, the iframe will automatically reload itself so that the changes can be shown to the user. Both pages are located in the same domain.
Firstly, you had a missing closing bracket ")" at the end of the $.get method.
The main problem, though, was probably that your server is not sending proper Last-Modified headers. The server I tested on didn't send any, meaning mod is undefined. A workaround is to check for Content-Length instead. It's not ideal because an edited page doesn't necessarily change size, but it seems you're in control of the page so you could ensure you add an extra byte to force a refresh.
Here is your checkModified function updated which should work:
function checkModified() {
$.get(page, function(a, b, x) {
var mod = (x.getResponseHeader('Last-Modified')) ? x.getResponseHeader('Last-Modified') : x.getResponseHeader('Content-Length');
if (lM != mod) {
lM = mod;
console.log('Fetched');
document.getElementById("frame").src += "";
}
});
}
Related
I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>
I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.
I have a web application where the user can generate PDF and PowerPoint files. These files may take some time to generate, so I would like to be able to display a loading animation while it generates. The problem here is that I have no mean to know when the download has started. The animation never goes away.
I am aware that it could be possible to generate the file "on the side" and alert the user when the file is ready for download using AJAX, but I prefer "locking" the user while he waits for the download to start.
To understand what needs to be done here, let's see what normally happens on this kind of request.
User clicks the button to request the file.
The file takes time to generate (the user gets no feedback).
The file is finished and starts to be sent to user.
What we would like to add is a feedback for the user to know what we are doing... Between step 1 and 2 we need to react to the click, and we need to find a way to detect when step 3 occurred to remove the visual feedback. We will not keep the user informed of the download status, their browser will do it as with any other download, we just want to tell the user that we are working on their request.
For the file-generation script to communicate with our requester page's script we will be using cookies, this will assure that we are not browser dependent on events, iframes or the like. After testing multiple solutions this seemed to be the most stable from IE7 to latest mobiles.
Step 1.5: Display graphical feedback.
We will use javascript to display a notification on-screen. I've opted for a simple transparent black overlay on the whole page to prevent the user to interact with other elements of the page as following a link might make him lose the possibility to receive the file.
$('#downloadLink').click(function() {
$('#fader').css('display', 'block');
});
#fader {
opacity: 0.5;
background: black;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="fader"></div>
Click me to receive file!
</body>
Step 3.5: Removing the graphical display.
The easy part is done, now we need to notify JavaScript that the file is being downloaded. When a file is sent to the browser, it is sent with the usual HTTP headers, this allows us to update the client cookies. We will leverage this feature to provide the proper visual feedback. Let's modify the code above, we will need to set the cookie's starting value, and listen to its modifications.
var setCookie = function(name, value, expiracy) {
var exdate = new Date();
exdate.setTime(exdate.getTime() + expiracy * 1000);
var c_value = escape(value) + ((expiracy == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = name + "=" + c_value + '; path=/';
};
var getCookie = function(name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == name) {
return y ? decodeURI(unescape(y.replace(/\+/g, ' '))) : y; //;//unescape(decodeURI(y));
}
}
};
$('#downloadLink').click(function() {
$('#fader').css('display', 'block');
setCookie('downloadStarted', 0, 100); //Expiration could be anything... As long as we reset the value
setTimeout(checkDownloadCookie, 1000); //Initiate the loop to check the cookie.
});
var downloadTimeout;
var checkDownloadCookie = function() {
if (getCookie("downloadStarted") == 1) {
setCookie("downloadStarted", "false", 100); //Expiration could be anything... As long as we reset the value
$('#fader').css('display', 'none');
} else {
downloadTimeout = setTimeout(checkDownloadCookie, 1000); //Re-run this function in 1 second.
}
};
#fader {
opacity: 0.5;
background: black;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="fader"></div>
Click me to receive file!
</body>
Ok, what have we added here. I've put the set/getCookie functions I use, I don't know if they are the best, but they work very well. We set the cookie value to 0 when we initiate the download, this will make sure that any other past executions will not interfere. We also initiate a "timeout loop" to check the value of the cookie every second. This is the most arguable part of the code, using a timeout to loop function calls waiting for the cookie change to happen may not be the best, but it has been the easiest way to implement this on all browsers. So, every second we check the cookie value and, if the value is set to 1 we hide the faded visual effect.
Changing the cookie server side
In PHP, one would do like so:
setCookie("downloadStarted", 1, time() + 20, '/', "", false, false);
In ASP.Net
Response.Cookies.Add(new HttpCookie("downloadStarted", "1") { Expires = DateTime.Now.AddSeconds(20) });
Name of the cookie is downloadStarted, its value is 1, it expires in NOW + 20seconds (we check every second so 20 is more than enough for that, change this value if you change the timeout value in the javascript), its path is on the whole domain (change this to your liking), its not secured as it contains no sensitive data and it is NOT HTTP only so our JavaScript can see it.
VoilĂ ! That sums it up. Please note that the code provided works perfectly on a production application I am working with but might not suit your exact needs, correct it to your taste.
This is a simplified version of Salketer's excellent answer. It simply checks for the existence of a cookie, without regard for its value.
Upon form submit it will poll for the cookie's presence every second. If the cookie exists, the download is still being processed. If it doesn't, the download is complete. There is a 2 minute timeout.
The HTML/JS page:
var downloadTimer; // reference to timer object
function startDownloadChecker(buttonId, imageId, timeout) {
var cookieName = "DownloadCompleteChecker";
var downloadTimerAttempts = timeout; // seconds
setCookie(cookieName, 0, downloadTimerAttempts);
// set timer to check for cookie every second
downloadTimer = window.setInterval(function () {
var cookie = getCookie(cookieName);
// if cookie doesn't exist, or attempts have expired, re-enable form
if ((typeof cookie === 'undefined') || (downloadTimerAttempts == 0)) {
$("#" + buttonId).removeAttr("disabled");
$("#" + imageId).hide();
window.clearInterval(downloadTimer);
expireCookie(cookieName);
}
downloadTimerAttempts--;
}, 1000);
}
// form submit event
$("#btnSubmit").click(function () {
$(this).attr("disabled", "disabled"); // disable form submit button
$("#imgLoading").show(); // show loading animation
startDownloadChecker("btnSubmit", "imgLoading", 120);
});
<form method="post">
...fields...
<button id="btnSubmit">Submit</button>
<img id="imgLoading" src="spinner.gif" style="display:none" />
</form>
Supporting Javascript to set/get/delete cookies:
function setCookie(name, value, expiresInSeconds) {
var exdate = new Date();
exdate.setTime(exdate.getTime() + expiresInSeconds * 1000);
var c_value = escape(value) + ((expiresInSeconds == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = name + "=" + c_value + '; path=/';
};
function getCookie(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function expireCookie(name) {
document.cookie = encodeURIComponent(name) + "=; path=/; expires=" + new Date(0).toUTCString();
}
Server side code in ASP.Net:
...generate big document...
// attach expired cookie to response to signal download is complete
var cookie = new HttpCookie("DownloadCompleteChecker"); // same cookie name as above!
cookie.Expires = DateTime.Now.AddDays(-1d); // expires yesterday
HttpContext.Current.Response.Cookies.Add(cookie); // Add cookie to response headers
HttpContext.Current.Response.Flush(); // send response
Hope that helps! :)
You can fetch the file using ajax add indicator then create a tag with dataURI and click on it using JavaScript:
You will need help from this lib: https://github.com/henrya/js-jquery/tree/master/BinaryTransport
var link = document.createElement('a');
if (link.download != undefined) {
$('.download').each(function() {
var self = $(this);
self.click(function() {
$('.indicator').show();
var href = self.attr('href');
$.get(href, function(file) {
var dataURI = 'data:application/octet-stream;base64,' + btoa(file);
var fname = self.data('filename');
$('<a>' + fname +'</a>').attr({
download: fname,
href: dataURI
})[0].click();
$('.indicator').hide();
}, 'binary');
return false;
});
});
}
You can see download attribute support on caniuse
and in your html put this:
generate
I found the answer by jcubic worked really well for my needs.
I was generating a CSV (plain text) so did not need the additional binary library.
If you need to do the same, here is how I adjusted it to work for plain text files.
$('.download').on('click', function() {
// show the loading indicator
$('.indicator').show();
// get the filename
var fname = $(this).attr('data-download');
$.get("/products/export", function(file) {
var dataURI = 'data:text/csv;charset=utf-8,' + file;
$('<a>' + fname + '</a>').attr({
download: fname,
href: dataURI
})[0].click();
// hide the loading indicator
$('.indicator').hide();
});
});
The filename is specified with data-download attribute in HTML on the tag with .download class.
When an iOS 8 device running a Web Application (i.e. launched from a shortcut on the Home Screen) returns from it's Sleep state all asynchronous web requests made fail to trigger the OnUpdateReady callback.
The problem is quite easy to reproduce - simply put the two code files below on any web server and give it a try.
Has anyone else run into this issue? If so is there any workarounds?
I'm posting this to try to attract attention to this bug in iOS 8 that has essentially ruined all of my web applications - we've had to recommend to NOT upgrade beyond iOS 7. And yes, I've posted the problem on Apple Bug Reporter but I think no one is looking at these since it has been a long time.
app.manifest
CACHE MANIFEST
# 2014-09-24 - Test
CACHE:
default.html
default.html
<!DOCTYPE html>
<html manifest="app.manifest">
<head>
<title>Test Harness</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<meta name="HandheldFriendly" content="true" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<script language="javascript" type="text/javascript">
var Test = new function () {
var _GetEnd = function (oResult) {
var sResult = ': ' +
((oResult.Value === true)
? 'Success'
: 'Failure<br>' + oResult.Reason) +
'<br>';
var oLog = document.getElementById('idLog');
oLog.innerHTML = (new Date()) + sResult + oLog.innerHTML
setTimeout(_GetBegin, 1000);
};
var _GetBegin = function () {
var sURL = 'app.manifest';
var hAsyncCallback = _GetEnd;
try {
var oRequest = new XMLHttpRequest();
oRequest.onreadystatechange =
function () {
if (oRequest.readyState != 4) return;
if (oRequest.status != 200) {
hAsyncCallback({ Value: false, Reason: oRequest.responseText });
} else {
hAsyncCallback({ Value: true, Reason: null });
}
};
oRequest.open('GET', sURL, true);
oRequest.send(null);
} catch (e) {
alert('Critical Error: ' + e.message );
}
};
this.Start = function () { _GetBegin(); }
};
</script>
</head>
<body onload="Test.Start();">
<ol>
<li>Put both app.manifest and default.html on a web server.</li>
<li>Make sure this page is being launched from the Home screen as a web application.</li>
<li>Press the sleep button while it is running.</li>
<li>Press the wake button and unlock the phone to get back to this screen.</li>
<li>Under iOS7x the page continues, under iOS8 the onreadystatechange never gets called again.</li>
</ol>
<div id="idLog"></div>
</body>
</html>
Installing iOS 8.1.1 fixes this.
I am also seeing the same issue, though my example is much simpler. Simply have a webclip application with
<script>
window.setInterval(function(){
console.log("Johnny Five Alive! : " + new Date());
},1000);
</script>
on the page. Inspecting the console, after the sleep wakes up, no more console output. This works fine on iOS7 (my actual application is a complicated angularJS thing, I just boiled down the issue to this). Have you had any response on your bug report?
Our workaround (for AJAX) is:
Detect iOS8 (indeed 8.0.2 still has this) (also see this for other workaround: How to resume JavaScript timer on iOS8 web app after screen unlock?)
Remove the normal eventListeners, but keep the onProgress one
...
this.onProgress = function(e)
{
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = 0.0;
if(total != 0)
{
percentage = position / total;
}
if(percentage == 1) {
if( this.isIOS8() ) {
recovery_uuid.get(uuid, _.bind(this.ios8ScriptReturn, this));
}
}
}
...
//this gets called when the script with this UUID is injected
this.ios8ScriptReturn = function(uuid, value) {
//then we create a simpler non real one
this.xhr = {};
this.xhr.readyState = 4;
this.xhr.status = 200;
this.xhr.responseText = value;
this.xhr.onreadystatechange = null;
this.xhr.isFake = true;
//fake stateChnage
this.onReadyStateChange();
}
add a UUID to each request
if( this.isIOS8() ) {
ajaxInfo.url += '&recoveryUUID='+ajaxInfo.uuid;
}
Then still perform the XHR Send (that actually works fine, server gets and send back fine).
server Side save the 'result' in database/file with the UUID as index/part of filename
//detect the need for saving the result, and save it till requested
if(isset($_GET['recoveryUUID'])) {
$uuid = $_GET['recoveryUUID'];
RecoveryUUID::post($uuid, $result_json_string);
}
On the client create a little helper global object that listens to the code injects and redirects them to the onProgress handler.
var RecoveryUUID = (function (_root) {
function RecoveryUUID() {
this.callbacks = {};
}
var proto = RecoveryUUID.prototype;
proto.onLoaded = null;
proto.set = function(uuid, value) {
console.log('RECOVERY UUID: Received DATA: '+uuid+' value: '+value);
if(typeof this.callbacks[uuid] != 'undefined') {
this.callbacks[uuid](uuid, value);
delete this.callbacks[uuid]; //auto remove
}
if(this.onLoaded != null) {
this.onLoaded(uuid, value);
}
var script = document.getElementById("recoveryScript_"+uuid);
script.parentElement.removeChild(script);
}
proto.getURL = function(uuid) {
return "http://"+window.location.hostname+":8888/recoveryuuid/index.php?uuid="+uuid;
}
proto.get = function(uuid, callback) {
var script = document.createElement("script");
script.setAttribute("id", "recoveryScript_"+uuid);
script.setAttribute("type", "text/javascript");
script.setAttribute("src", this.getURL(uuid));
if(typeof callback != 'undefined') {
this.callbacks[uuid] = callback;
}
document.getElementsByTagName("head")[0].appendChild(script);
}
return RecoveryUUID;
})();
//global - just so the injected script knows what to call
recovery_uuid = new RecoveryUUID();
The script that is loaded immediately executes (pushes, since setInterval is dead as well).
// this is: http://"+window.location.hostname+":8888/recoveryuuid/index.php?uuid=...."
<?php
header('Cache-Control: no-cache, no-store, must-revalidate, post-check=0, pre-check=0 '); // HTTP 1.1. //iOS force this file to keep fresh
header('Pragma: no-cache'); // HTTP 1.0.
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header('Content-type: application/javascript; charset=UTF-8');
if(isset($_GET['uuid'])) {
$uuid = $_GET['uuid'];
$out = 'recovery_uuid.set('.json_encode($uuid).','.json_encode(RecoveryUUID::get($uuid)).');';
echo $out;
}
?>
Below is a simple filebased results implementation.
<?php
class RecoveryUUID {
static public function getFileName($uuid) {
return SOMESTATIC LOCATION.$uuid.'.json';
}
static public function post($uuid, $stdClassOrString) {
$data = '{ "data": '.json_encode($stdClassOrString).', "uuid": '.json_encode($uuid).' }';
file_put_contents(self::getFileName($uuid), $data);
}
//might not work first time as the script tag might request this file before it was written.
//so we wait just a bit.
static public function getFull($uuid) {
$tries = 10;
$filename = self::getFileName($uuid);
while ($tries > 0) {
if(file_exists($filename)) {
if (is_readable($filename)) {
$data = #file_get_contents($filename);
if($data !== FALSE) {
unlink($filename);
return $data;
}
}
}
$tries = $tries -1;
usleep(250000);//wait 0.25 secs ...
}
$data = new stdClass();
$data->uuid = $uuid;
$data->data = 'ERROR RECOVERYUUID: timeout on reading file';
return $data;
}
static public function get($uuid) {
$decoded = json_decode(self::getFull($uuid));
if( $decoded->uuid == $uuid ) {
return $decoded->data;
}
return null;
}
}
?>
As we do not use JQuery all we needed to do was add the extra logic in our Ajax class, and of course the Saving to Database for all requests..
Downsides:
Nasty
Will keep on adding memory footprint for each call (for us not an issue as the memory is cleared between window.location.href calls (we do not use SPA) so eventually will fall over.
Extra serverside logic.
Upsides:
Works until memory runs out (removing script tags, which we do does not remove the memory associated)
Comments:
You could of course just send everything with the 'call' but we wanted to have minimal server side impact (or not much work for us anyway) + we presume this will be fixed and means our 'user' code has 0 impact.
Weird, Apple just closed my bug and referred to the same bug number. Also a web app but I found css3 transitions to stop working after screen lock see below:
Engineering has determined that your bug report (18556061) is a duplicate of another issue (18042389) and will be closed
My report:
If you add an HTML app to the home screen and open it, all CSS3 transitions work correctly. Without closing the app and pressing screen lock the transitions seem to stop and can cause the ui to appear to freeze. For example if an absolute overlay is triggered (opacity:0 to opacity:1) it remains invisible making the app appear not to work
Ajax requests, Timer functions and WebkitAnimation are broken after a lock-screen on iOS8.
For the Ajax and Timer functions, we are using this solution in our system:
How to resume JavaScript timer on iOS8 web app after screen unlock? (link to the gitHub in the comment).
It is not exactly part of the question but I would like to share our workaround with CSS3 animations and events, since it may help somebody in the future.
For the webkitAnimation, we found that redrawing the element with the animation on, or more drastically the body would restart animations and events applied to them (webkitAnimationEnd for instance, which is used heavily by jquery-mobile).
so our code gives something like:
document.body.style.display='none';
setTimeout( function() { document.body.style.display = 'block'; }, 1);
You may or may not need the setTimeout function on the second statement. Most interesting thing is, once it has been redrawn, it will never go frozen again no matter how many lock screens come up after that...
The webapp environment is so horribly broken when resuming after screen lock I don't see how (a) Apple could ignore this indefinitely and (b) how any webapp can confidently work around the crippled environment.
My solution is to detect resume after sleep using setInterval (which stops working after the resume) and then posting an alert() to the user stating that the app has to be re-launched from the home screen because iOS cannot resume it.
It just so happens that alert() is also broken after the resume--it displays the alert and then the webapp exits to the home screen when the user hits OK! So this forces the user to re-launch.
The only issue when the user re-launches is the handling of apple-mobile-web-app-status-bar-style. I have this set to black-translucent which normally sets the status bar content to black (on light backgrounds) or white (on dark backgrounds). On the first re-launch after resume, the status bar content is always black. On subsequent re-launches (not interrupted by sleep/resume) the behavior returns to normal.
What a mess. If I was responsible for this at Apple I'd be embarrassed, and here we are with 8.1 and it still hasn't been fixed.
I am trying to dynamically adjust the height of an iFrame on a web page depending on the content within the iFrame via some JavaScript.
My problem is when I have the script directly on the page in a <script> tag it works fine. When I stuff the code in to a separate js file and link to it- it doesn't work!
<iframe id='StatusModule' onload='FrameManager.registerFrame(this)' src='http://randomdomain.dk/StatusModule.aspx'></iframe>
<script type='text/javascript' src='http://randomdomain.dk/FrameManager.js'></script>
It gives me the error:
Uncaught ReferenceError: FrameManager is not defined
Can this really be true? Has it something to do with the page life cycle?
Ps. I guess the JavaScript code is irrelevant, as we not it works.
UPDATE: I think this might have something to do with secure http (https) and the different browsers in some weird way. I noticed that the script actually worked in Firefox. Or rather I'm not sure if its the script, or just Firefox's functionality that resizes iframes automatically depending on the content. It doesn't give me any error though.
If I then add https to the script url reference, the scripts work in IE and Chrome - but not in Firefox. Function reference error! This just got weird!
UPDATE #2: Its not a Firefox function that resizes the iframe. Its the actual script that works (without https).
UPDATE #3: The JavaScript. Works fine if I put it directly into a script tag.
var FrameManager = {
currentFrameId: '',
currentFrameHeight: 0,
lastFrameId: '',
lastFrameHeight: 0,
resizeTimerId: null,
init: function () {
if (FrameManager.resizeTimerId == null) {
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 0);
}
},
resizeFrames: function () {
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight: function () {
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0)) {
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0)) {
if (pair[0] == 'frameId') {
if ((pair[1] != null) && (pair[1].length > 0)) {
FrameManager.currentFrameId = pair[1];
}
} else if (pair[0] == 'height') {
var height = parseInt(pair[1]);
if (!isNaN(height)) {
FrameManager.currentFrameHeight = height;
//FrameManager.currentFrameHeight += 5;
}
}
}
}
}
},
registerFrame: function (frame) {
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1) {
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '&frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 0);
UPDATE #4: Alright I did as ShadowWizard and TheZuck suggested:
<script type="text/javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.randomdomain.dk/StatusWebModule.aspx";
iframe.width = '100%';
iframe.id = 'StatusModule';
iframe.scrolling = 'no';
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
FrameManager.registerFrame(iframe);
});
} else {
iframe.onload = function () {
FrameManager.registerFrame(iframe);
};
}
document.getElementById('framecontainer').appendChild(iframe);
</script>
With HTTP as URL its work on IE and Firefox - not Chrome. If I set it to HTTPS it works on Chrome and IE - Not Firefox. Same error:
"ReferenceError: FrameManager is not defined".
What is going on here?
a couple of things:
I would bet on a race condition when you have two independent
resources which are supposed to be loaded concurrently. You can
easily check this by writing to log (or to document, whichever works
for you) when both finish loading (i.e. add a little script in the
iframe to dynamically add the time to the content or write to log if
you're using chrome, do that in the external script file as well,
and see if they post the time in a specific order when this fails). In your case, if the script appears before the iframe, and you don't mark it as async, it should be loaded before the iframe is fetched, so it would seem strange for the iframe not to find it due to a race condition. I would bet on (3) in that case.
Assuming there is such an issue (and if there isn't now, when you go
out into the real world it will be), a better way to do this is to
make sure both behave well in case the other loads first. In your
case, I would tell the iframe to add itself to a local variable
independent of the script, and would tell the script to check if the
iframe registered when it loads, and after that in recurring
intervals until it finds the iframe.
If the page the script is loaded into is not in the same domain
as the iframe (note that it doesn't matter where the script comes
from, it only matters what the page's domain is), (or even the same
protocol as someone mentioned here), you will not be able to access
the content so you won't be able to resize according to what the
content is. I'm not sure about the onload method, if it's considered part of the wrapping page or part of the internal iframe.
Check out this question, it sounds relevant to your case:
There's also an interesting article here about this.
I think that your frame is loaded before the script, so "FrameManager" does not exist yet when the iframe has finished loading.