I have an HTML video that plays full screen when the user clicks play. If the user hits escape inside of full screen, everything works properly - the video stops playing and exits full screen. However, if the user pauses the video inside of full screen and then hits escape, the video starts playing again causing the sound from the video to loop over the page that is returned to upon exiting full screen. My js controls are as follows:
exitHandler: function(){
vid = Video.vid;
$(Video.featuredVideo).toggleClass('featured-video-show');
if (document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement !== null){
if (vid.paused){
vid.play();
}
else {
vid.pause();
}
}
}
How can I stop the video/audio from starting back up if a user pauses inside of full screen and then hits 'escape' to exit full screen?
Create a variable to keep track of whether you are currently (at the time of handler's execution) exiting or entering fullscreen, and don't fire the play command if you are indeed exiting it. I don't think there are specific event listeners for this, so you may have to write an interval for this. When I faced this issue, I used the following function:
var canFullscreen = function(){
return (
!document.fullscreenElement &&
!document.mozFullScreenElement &&
!document.webkitFullscreenElement &&
!document.msFullscreenElement );
}
This function checks whether we can currently enter fullscreen. If it returns false, then either there is no fullscreen capability (old/weird browser), or you are already in fullscreen. This is the function I ran in the interval to check exactly when the user exits fullscreen (and at that point handled the exit programmatically). If you are instead tracking the keypress of the Escape button, you may put that function there to determine whether you're entering or exiting fullscreen.
Related
Following Mozilla's API document on Fullscreen, I've placed the following code in my website, it simply takes the whole document (html element) and makes the page go fullscreen once the user clicks anywhere in the page, and once there's another click, page goes back to normal.
var videoElement = document.getElementsByTagName('html')[0];
function toggleFullScreen() {
if (!document.mozFullScreen) {
if (videoElement.mozRequestFullScreen) {
videoElement.mozRequestFullScreen();
}
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false);
My question is how can I save this fullscreen state so every time that Firefox loads up, that page is still on fullscreen.
Or any workaround? This is for Firefox for Android.
It's an extreme workaround, but you can make your website a progressive web app and put "display": "fullscreen" in its manifest. Then you can launch your site from the home screen and use it like a fullscreen native app.
Following my experiments and the specs, this isn't doable, from client browser javascript
This api need an user interaction. We can't activate the fullscreen by scripting.
From the fullscreen api specification:
Fullscreen is supported if there is no previously-established user
preference, security risk, or platform limitation.
An algorithm is allowed to request fullscreen if one of the following
is true:
The algorithm is triggered by user activation.
The algorithm is triggered by a user generated orientation change.
https://fullscreen.spec.whatwg.org/#model
About activation events:
An algorithm is triggered by user activation if any of the following
conditions is true:
The task in which the algorithm is running is currently processing an
activation behavior whose click event's isTrusted attribute is true.
The task in which the algorithm is running is currently running the
event listener for an event whose isTrusted attribute is true and
whose type is one of:
change
click
dblclick
mouseup
pointerup
reset
submit
touchend
https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
We can't trigger fullscreens from scripts, or if so, the script must be triggered by the user.
Including simulating a click won't works, this is regular behavior, made to protect user experience.
With some reflexion, we can't agree more on this, imagine any ads page can launch full screens, the web would be a hell to browse!
You told in comment: «I am the only user here»
What you can do if using unix: (( probably alternatives exists in other os )).
Using midori (a lightweight webkit browser), this will start a real fullscreen.
midori -e Fullscreen -a myurl.html
There is no ways to start firefox or chromium in a fullscreen state from the command line, to my knowledge.
But what is doable is to trigger a F11 click at system level, focusing on the good window, just after the page launch. ((sendkey in android adb shell?))
xdotool can do that.
Here is a pipe command line that will launch firefox with myurl.html, search for the most recent firefox window id, then trigger the F11 key on this window.. (Press F11 again to exit)
firefox myurl.html && xdotool search --name firefox | tail -1 | xdotool key F11
This should be easy to adapt for other browsers.
As last alternative, have a look at electron or nw.js.
take a look at this add on for Firefox, i have not tried it, as I'm posting this from mobile, it's description does say that it can force start in full screen. I'm just quoting their description .
Saves the last state or force start in full screen forever! Simple and
complete for this purpose.
Edit : And the link to it
https://addons.mozilla.org/en-US/firefox/addon/mfull/
What about using localStorage like this?
function goFullScreen() {
if (videoElement.mozRequestFullScreen) {
localStorage.setItem('fullscreenEnabled', true)
videoElement.mozRequestFullScreen();
}
}
window.onload = function () {
if (localStorage.getItem('fullscreenEnabled') === true) {
goFullScreen();
}
};
function toggleFullScreen() {
if (!document.mozFullScreen) {
goFullScreen();
} else {
if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
localStorage.setItem('fullscreenEnabled', false)
}
}
}
window.addEventListener("click", function(e) {
toggleFullScreen();
}, false)
I have key event bindings for the arrow keys on a web page. These bindings work perfectly as the page loads, but suddenly stop working when the Google AdSense advertisement on the page loads. This doesn't happen on every page/ad load, but on about half of them.
When this happens, if I press the arrow keys repeatedly during page load, the bound event will fire successfully until the ad appears, at which point the event stops working, and the key's default action (scrolling the page) begins to occur as I keep pressing the key. This is strange since I have disabled the default action on these keys via:
window.onkeydown = function(e) {
// Spacebar, all four arrow keys
if (e.keyCode == 32 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 ||
e.keyCode == 40) {
e.preventDefault();
return false;
}
};
If I subsequently click anywhere on the page body, the key bindings will start working again.
I'm guessing that perhaps when the ad finishes loading (which is after the rest of the page), it causes some kind of interrupt that "steals focus" from the page (but apparently not the window since the scrolling still happens?).
The actual keybindings are done using Mousetrap, though that doesn't seem to have anything to do with the problem, and I have only encountered this issue in Google Chrome. I do not get this behavior in Firefox. If I enable AdBlock on Chrome, the issue does not occur, further showing it's the advertisement triggering this "interruption."
Is there anything obvious that I'm unaware of that can completely interrupt keybindings in this way, while still allowing keys to scroll the page until the user clicks in the body again? Is there any way to prevent the advertisement from disrupting the user's interactivity with the page in this way?
One suggestion was to capture the AdSense ADS_LOADED event, but this appears to be available only when using the Google IMA SDK in videos.
The solution I came up with was to listen for all blur events, and when focus is stolen from the document body by an advertisement, return focus to the window. This only works when window.focus() is wrapped in a timeout, something I currently don't understand.
The isDescendant() function was taken from this answer.
function isDescendant(child, parent) {
/*
Test if child is contained within parent regardless of how many levels deep
*/
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
window.addEventListener('blur', function() {
var ads = document.getElementsByClassName('ad');
var n = ads.length;
for (i=0; i<n; i++) {
if (isDescendant(document.activeElement, ads[i])) {
// This only works if wrapped in a timeout (why?)
window.setTimeout(function () {
window.focus();
}, 0);
break;
}
}
});
Hi i have notification div(divNotify) with some information and a timer in masterpage
Protected Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Me.GetNotification_Stats()
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "Alert", "Show_NotifyDiv();", True)
Catch ex As Exception
Me.lblError.Visible = True
Me.lblError.InnerText = ex.Message
End Try
End Sub
divNotify will display in some interval of time.
here i need when the user will minimize the browser he will be notified by blinking browser and change color of browser
but first of all how do i know if the browser is minimized or not in javasript
here i am using jquery for show div tag
function Show_NotifyDiv() {
$("#div_NotificationOuter").show(1000);
$("#div_NotificationOuter").animate({ bottom: '+=30px' }, 4000);
}
Its impossible to find out whether the page is minimized via JavaScript, but you can use Visibility API to determine, whether the page is visible to user or not.
Currently available in Chrome, Mozilla and IE10.
https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
http://code.google.com/chrome/whitepapers/pagevisibility.html
http://www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.
Notes: The Page Visibility API is especially useful for saving
resources and improving performance by letting a page avoid performing
unnecessary tasks when the document isn't visible.
When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.
Use cases
Let's consider a few use cases for the Page Visibility API.
A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page
An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible
A page wants to detect when it is being prerendered so it can keep accurate count of page views
A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)
Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.
Example
View live example (video with sound).
The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var videoElement = document.getElementById("videoElement");
// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if (document[hidden]) {
videoElement.pause();
} else {
videoElement.play();
}
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
// When the video pauses, set the title.
// This shows the paused
videoElement.addEventListener("pause", function(){
document.title = 'Paused';
}, false);
// When the video plays, set the title.
videoElement.addEventListener("play", function(){
document.title = 'Playing';
}, false);
}
Source: MDN: Page Visibility API
Additionally to c69's Answer, I would propose the library isVisible.
It has utility functions to access the W3C Page visibility API and you do not have to worry about cross browser support (unifies moz- or webkit-prefixed functions)
maybe check the size of the window? i'm just guessing.
We will be patient, but visibilityState is coming:
W3C defines the visibility state
I use the MediaElement.js framework to build my audio players...
But, is a podcast and is normal see users closing the window accidentally.
I'm searching for scripts to this, but absolutely nothing works.
How alert the user when he close the window with the player working...?
If is playing: ask if the user really want this.
If the player isn't playing: close the window..
Add an event as follows:
$(window).bind("beforeunload", function(evt) {//gets called before the user leaves the page
//check if audio is already running
if(isPlayingAudio()) {
//shows a confirm message asking user if they want to stay
return "Are you sure you want to leave while playing music?";
}
})
If your elements are on the page and not stored in javascript
function isPlayingAudio() {
var $playing = $('audio').filter(function(i, $audio) {//all audio not paused
return !$audio.prop('paused');
});
return $playing.length === 0;//no audio elements are playing...
}
I'm having a problem preloading HTML5 audio content and then using what I have in cache rather than attempting to redownload the audio every time I try to replay it.
http://cs.sandbox.millennialmedia.com/~tkirchner/rich/K/kungFuPanda2_tj/
The experience is suppose to be that when someone clicks on the banner, it pops up an ad with a loading bar. THe loading bar is loading all the images necessary for the animation. In the meantime, the audio is also getting loaded via audio tags already on in the DOM (which is fine). After all the images are loaded, the loading bar disappears and the user can continue on. There are 4 buttons on the bottom of the screen that they can click. Clicking one of them plays the audio file and images do a flipbook-style animation thats synced to the audio.
Audio Tags:
<audio id="mmviperTrack" src='tigress.mp3'></audio>
<audio id="mmmantisTrack" src='viper.mp3'></audio>
<audio id="mmtigressTrack" src='kungfu3.mp3'></audio>
<audio id="mmcraneTrack" src='crane.wav'></audio>
Play Button Event Listeners:
button.addEventListener('click',function(){
if ( f.playing ) return false;
f.playing = true;
button.audio.play();
},false);
button.audio.addEventListener('playing', function(){
animate();
}, false);
The problem is, in javascript, everytime I click play(), it reloads the audio file and then plays it. I can't seem to get it to load the audio once in the beginning and go off of whats stored in memory rather than try to reload the audio every single time I click the button.
I've tried experimenting with the preload and autobuffer properties, but it seems that mobile safari ignores those properties, because no matter what I set them too, the behavior is always the same. I've tried experimenting with source tags and different file formats... nothing.
Any ideas?
Alright, so the solution was a bit of a hack, cheat, workaround, whatever you want to call it.
What I noticed is that if I hit the play button on an audio file that I just played, it doesn't reload itself. It could be because I paused the audio after it finished playing through, but I'm not 100% sure on that. In any case, what I did is I combined all 4 audio files into one large audio file (yay Audacity~!). Then, every time I hit one of the play buttons I would set the currentTime property of the audio object to whatever the starting point of that track and then play the track until it hit its ending point, and then pause it again. Mission accomplished! Loaded once in the beginning and never again for each play.
Not crazy about the idea that I had to combine all the different audio tracks, but hey it works.
Oh, also. To get the audio track to load and fire a "canplaythrough" event, I attached this function to a user click event:
var track;
function addHTMLAudio() {
track = document.createElement('audio');
track.id = 'mm_audio'
track.autoplay = false;
track.preload = false;
track.addEventListener('canplaythrough',function(){
track.removeEventListener('canplaythrough');
audioLoaded = true;
},false);
document.getElementById('body').appendChild(track);
track.src = f.trackURL;
track.play();
setTimeout(function(){ track.pause(); },1);
}
playButton.addEventListener('click',function(e){
if ( playStatus > 0 ) return;
playStatus = 1;
var myId = e.target.parentNode.id;
var myClip = findClip( myId );
myClip.state = 'active';
track.currentTime = myClip.tIndex.start;
track.play();
runAnimation(myClip);
},false);