HTML5 video canPlay event not working second time - javascript

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" />

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.

Errors in parsing a webpage using jQuery?

I am trying to parse a webpage using jQuery. This is my code:
$.get(u, function(data)
{
console.log(data);
$(data).find('meta').each(function()
{
console.log($(this).text());
//alert($(this).text());
alert($(this).attr('content'));
console.log($(this).attr('content'));
});
});
The page source is here.
There are many meta tags in this page but its only able to parse 6 of them namely :
<meta property="og:type" content="website" />
<meta property="og:title" content="Affect and Engagement in Game-BasedLearning Environments" />
<meta property="og:description" content="The link between affect and student learning has been the subject of increasing attention in recent years. Affective states such as flow and curiosity tend to have positive correlations with learning while negative states such as boredom and frustrat..."/>
<meta property="og:url" content="http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=6645369" />
<meta property="og:image" content="http://ieeexplore.ieee.org/assets/img/logo-ieee-200x200.png" />
<meta property="og:site_name" content="IEEE Xplore" />
<meta property="fb:app_id" content="179657148834307" />
What am I doing wrong?
jQuery will skip all meta-Tags which do not have closing brackets.
You therefore would be forced to parse the response using a regular expression, but this is in fact ugly.
It's very sad, that we still live in a world where there is such HTML out there.
If you really want to go that path, you could do some thing like this
data = data.replace(/(<meta.*[^\/])>/g, "$1/>");
before doing the "find" on it.
You must append the response to an element and then get the meta.
$(data).appendTo("#test");
var m = $('#test').find('meta');
alert(m.length);
$('#test').html(''); // delete content
Example: http://jsfiddle.net/B4ATz/

How to hide the safari address bar on mobile devices [duplicate]

How do I hide the address bar on iPhone?
I tried two different methods so far:
The scroll down one pixel trick with JavaScript on page load
And the following meta tags:
<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" />
Also this:
<meta names="apple-mobile-web-app-status-bar-style" content="black-translucent" />
I am completely confused.
PS: Oh, I forgot a really important thing: the web page itself does not overflow the browser window. It probably is the reason why the 1 pixel scrolldown trick does not work.
I can't make it bigger, since the hit thing about the design, that everyone can scroll, but this page folds... :)
I just hit this myself. If the address bar is not hiding, the reason may simply be the page is not long enough to scroll.
When the
window.scrollTo(0,1)
is called the page MUST be longer than the window so a scrolling event can occur.
Only when the scrolling even occurs will mobile safari hide the address bar.
đź”´ UPDATE: Apple removed support for minimal-ui in iOS 8 so this is no longer a useful answer :(
For new googlers looking into this: As of iOS 7.1 there's a new minimal-ui mode that works on mobile Safari:
It's enabled by setting the minimal-ui property on the viewport:
<meta name="viewport" content="minimal-ui">
You can also use it in conjunction with other properties like so:
<meta name="viewport" content="width=device-width, minimal-ui">
Of note, there's no minimum content length requirement as there is with the scrollTo hack. There's a great overview of this new mode here. (That's where the above image comes from.) He also lists some shortcomings.
The only official documentation I could find on this is a note in Apple's iOS 7.1 release notes:
A property, minimal-ui, has been added for the viewport meta tag key that allows minimizing the top and bottom bars on the iPhone as the page loads. While on a page using minimal-ui, tapping the top bar brings the bars back. Tapping back in the content dismisses them again.
For example, use <meta name="viewport" content="width=1024, minimal-ui”>.
Of course, since this only works in iOS 7.1 and above, it's usefulness may be limited.
Unless something has changed in recent iOS versions, the scroll down trick is the only one that reliably works, I've had no issues with this version:
/mobile/i.test(navigator.userAgent) && !location.hash && setTimeout(function() {
window.scrollTo(0, 1);
}, 1000);​
I didn't care about any other mobile platform for this particular page though, it was redirecting based on agent...you may want to change the regex to check for iPhone specifically, e.g. replace /mobile/ with /iPhone/.
I think this version is actually better. It tests to see if the user has already begun scrolling, which is an issue I noticed in my mobile project.
/Mobile/.test(navigator.userAgent) && !location.hash && setTimeout(function () {
if (!pageYOffset) window.scrollTo(0, 1);
}, 1000);
You can run the function when the site content is ready instead of using timeout
addEventListener("load", function() {
window.scrollTo(1, 0);
}, false);
Try:
setTimeout(function () {
window.scrollTo(0, 1);
}, 1000);
If using jQuery, put it at the end of $(document).ready();. The time-out allows for the browser to determine the height of the page...
In case none of these solutions work and you are running into the very narrow issue that I faced, here's what fixed it for me.
I had this in my CSS
html{position: relative; height: 100%; overflow: hidden;}
This css applies a fix to one of my pages only, so I restricted it with a condition to that page, and the address bar is now behaving correctly on all other pages.
I have been searching around on this full screen web app as well and i found this.
http://www.onlywebpro.com/2015/07/19/optimizing-full-screen-mobile-web-app-for-ios/
Basically you need add the following in your header:
<meta name="viewport" content = "width = device-width, initial-scale = 1.0, minimum-scale = 1, maximum-scale = 1, user-scalable = no" />
//App name
<meta name="apple-mobile-web-app-title" content="App name" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
//APP ICONS
<link rel="apple-touch-icon" href="/img/icon.png">
<link rel="apple-touch-icon" sizes="76x76" href="/img/icon.png">
<link rel="apple-touch-icon" sizes="120x120" href="/img/icon.png">
<link rel="apple-touch-icon" sizes="152x152" href="/img/icon.png">
Open the site in Safari
Tap on the "Open with" icon ( arrow pointing upwards and box below it) beside refresh button at the URL bar
Select "Add to home screen"
Go to the homescreen and open the "App name"
Voila! website with no URL bar or navigation buttons!
<meta name="apple-mobile-web-app-capable" content="yes" />
iPhone Configuring Web Applications
I think it will never be solved unless the content is more than the browser window.
Here is some code that will hide the URL on load, on orientation change, and on a touchstart (the touchstart should only be used if you have a persistent hidden URL, which is a whole other can of worms - if you don't, remove that part of the script).
if( !window.location.hash && window.addEventListener ){
window.addEventListener("load", function() {
setTimeout(function(){
window.scrollTo(0, 0);
}, 0);
});
window.addEventListener( "orientationchange",function() {
setTimeout(function(){
window.scrollTo(0, 0);
}, 0);
});
window.addEventListener( "touchstart",function() {
setTimeout(function(){
window.scrollTo(0, 0);
}, 0);
});
}
<meta charset="utf-8"><meta name="description" content="{MF_PLUGIN_SETTING:HOME_DESCRIPTION}"/><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"/><meta name="apple-mobile-web-app-capable" content="yes"><meta name="mobile-web-app-capable" content="yes">
This is used for adding a ios web app to the homescreen without the searchbar.

Stopping the page refresh - not working with clear function

This is code to display a spinner while image is loading and then show the image when it is done. Also, this page needs to be auto-refreshed every 5 seconds and the refreshing to be stopped at 11 seconds, ie refresh twice alltogether. But this doesn't work. The spinner code is in the css file. This does not work - keeps refreshing over and over - the timeout gets reset, tried using var to assign as well no joy. Any help appreciated highly.
<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">
<html>
<head>
<link rel="stylesheet" href="/css/graph.css" type="text/css" media="screen, projection">
<script src="/javascript/jquery-latest.js" type="text/javascript">
</script>
<script type="text/javascript">
var img = new Image(); img.height=600; img.width=2000;
$(img).load(function () {
$(this).css('display','none');
$(this).animate({ opacity: 0.25 }).fadeIn("slow");
$('#loader').append(this);
$(this).animate({ opacity: 1 })
}).error(function () {
}).attr('src', 'xyz.png');
var timer = function() { window.location.reload(true);};
window["reload_timer"] = setTimeout(timer, 5000);
var timer2 = function() {
clearTimeout(window["reload_timer"]);
clearTimeout(window["reload_timer2"]);};
window["reload_timer2"] = setTimeout(timer2, 11000);
</script>
</head>
<body id = "page"><div id="loader" class="loading">
</div>
</body>
</html>
You could try reloading the page URL with a parameter attached to it. Then you could read in the parameter with JavaScript and use that to know how many times the page has refreshed so you stop after 2 refreshes.
Otherwise the page is stateless - the same exact page will load as before, with no knowledge if it was already loaded or not. By introducing this URL parameter you can track some sort of state.
When you reload the page, the page forgets it has already been reloaded, so in fact your code never reaches timer2

Refresh iFrame (Cache Issue)

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);
}

Categories