Native Fullscreen JavaScript API (plus jQuery plugin)


HTML5 <video> is great, but when it was first released, one of the big complaints was that it couldn’t do true FullScreen like Flash. Thankfully, this is changing and native FullScreen support is coming to most browsers in the next few months (no word from the Internet Explorer team Update on IE below #5))
The API is still heavily in flux especially since the W3C joined in this week. I spent some time working through the differences to implement FullScreen in MediaElement.js HTML5 video player, and it’s working great in Safari 5.1+, Chrome Canary Chrome 15+, or Firefox Nightly (go to about:config and set full-screen-api.enabled= true) and scheduled for Firefox 10. Below I’m going to try to explain how things evolved, where we are today, and then some code that you can play with.
Simple Demo Video Demo

A Brief History of the FullScreen API

  1. The first native FullScreen implementation appeared in Safari 5.0 (and iOS) added a a webkitEnterFullScreen() function that only worked on <video> tags using Safari’s video controls (see Apple’s HTML5VideoElement).
  2. For Safari 5.1, Apple changed the API to be more inline with Mozilla’s FullScreen API proposal (which actually predates Apple’s implementation). Now, webkitRequestFullScreen() can be called on any DOM element which makes that portion of an HTML page go fullscreen.
  3. Firefox and Chrome announced that they will add FullScreen API support, and the feature has already arrived in Chrome Canary Chrome 15+ and Firefox Nightly (scheduled for Firefox 10). The Mozilla team has posted some a demo.
  4. On October 15, 2011, the W3C released a Fullscreen API proposal (written by a member of the Opera team) which has two main differences from Mozilla’s proposal:
    1. Mozilla/Webkit uses a Capital ‘S’ (FullScreen) while W3C does not (Fullscreen)
    2. Mozilla/Webkit uses cancelFullScreen
      while W3C uses exitFullscreen
  5. Update (11/15/2011): Ted Johnson from IEBlog says IE10 will not support the FullScreen API (12/05/2011: I misunderstood the first email from Ted) that the IE10 team has not yet decided whether to implement the FullScreen API. He notes however that, “Windows 8 Metro style Internet Explorer is always full screen … and as before, F11 enters full screen mode in desktop versions of IE.”

Understanding the FullScreen API

Here are the most important parts of the FullScreen API with notes on how things differ among browsers. In general, I’m using the Mozilla/Webkit spelling in the examples below, but I’m also noting the W3C differences where needed.

1. Detecting FullScreen support

To detect fullscreen support, you’ll need to use the typeof command to find out if a given browser has support for the FullScreen API methods. There is also boolean property called fullScreenEnabled that tells you if the user has disabled the feature (strangely WebKit does not have the fullScreenEnabled property making it difficult to detect if it’s turned off).

// Mozilla's proposed API: in practice, you'll need vendor prefixes (see examples below)
if (typeof document.cancelFullScreen != 'undefined' && document.fullScreenEnabled === true) {
    /* do fullscreen stuff */
}

2. Entering and Exiting FullScreen

To enter FullScreen mode, you call requestFullScreen (or requestFullscreen for W3C) on the element want to be viewed in FullScreen. To exit you call cancelFullScreen (or exitFullscreen for W3C) on the document object.

// mozilla proposal
element.requestFullScreen();
document.cancelFullScreen(); 
// Webkit (works in Safari and Chrome Canary)
element.webkitRequestFullScreen(); 
document.webkitCancelFullScreen(); 
// Firefox (works in nightly)
element.mozRequestFullScreen();
document.mozCancelFullScreen();
// W3C Proposal
element.requestFullscreen();
document.exitFullscreen();

Mozilla has also proposed an alternate requestFullScreenWithKeys() method which would enable the user to use the keyboard in FullScreen mode. With Flash, Adobe always disabled keyboard support in FullScreen to prevent malicious sites from attempting to steal passwords, but it looks like the browser makers are considering making this an option.

3. Fullscreen Event and Current Status

To detect when a FullScreen event happens, there is a fullscreeneventchange that fires on the element going FullScreen and a boolean property (fullScreen) on the document object that reports if it’s in FullScreen mode or not.

element.addEventListener('fullscreeneventchange', function(e) {
    if (document.fullScreen) {
       /* make it look good for fullscreen */
    } else {
       /* return to the normal state in page */
    }
}, true);
// note: unlike Webkit and the W3C proposal,
// Mozilla fires its mozfullscreenchange event on the *document* object
// instead of the element going fullscreen

Mozilla also mentions the possibility of adding a fullscreendenied event in the future. You should also know that Webkit added an ‘Is’ to their boolean property and that the W3C proposal strangely does not include this property:

// Mozilla proposal
document.fullScreen;
// Firefox (Nightly)
document.mozFullScreen;
// Webkit (Chrome, Safari)
document.webkitIsFullScreen; // note the 'Is'
// W3C proposal
// None? Why?

4. Styling FullScreen

Both Mozilla and the W3C have proposed new pseudo CSS classes for styling elements in FullScreen mode.

/* normal state */
.my-container {
    width: 640px;
    height: 360px;
}
/* Mozilla proposal (dash) */
.my-container:full-screen {
    width:100%;
    height:100%;
}
/* W3C proposal (no dash) */
.my-container:fullscreen {
    width:100%;
    height:100%;
}
/* currently working vendor prefixes */
.my-container:-webkit-full-screen, .my-container:-moz-full-screen {
    width:100%;
    height:100%;
}

5. Embedding FullScreen

When you embed content from another site (like a YouTube video) using Flash’s <object><embed> tags, you can specificy whether or not to allow FullScreen to work. This feature has also been added to the <iframe> tag using the allowFullScreen attribute.

<!-- content from another site that is allowed to use the fullscreen command -->
<iframe src="http://anothersite.com/video/123" width="640" height="360" allowFullScreen></iframe>

Putting it All Together

To make this work in its current state, you need a wrapper that can help detect the right features. Here’s what I’ve put together to work in Safari 5.1, Chrome Canary Chrome 15+, and Firefox Nightly. I’ll update it if the W3C notation goes through:

(function() {
	var
		fullScreenApi = {
			supportsFullScreen: false,
			isFullScreen: function() { return false; },
			requestFullScreen: function() {},
			cancelFullScreen: function() {},
			fullScreenEventName: '',
			prefix: ''
		},
		browserPrefixes = 'webkit moz o ms khtml'.split(' ');
	// check for native support
	if (typeof document.cancelFullScreen != 'undefined') {
		fullScreenApi.supportsFullScreen = true;
	} else {
		// check for fullscreen support by vendor prefix
		for (var i = 0, il = browserPrefixes.length; i < il; i++ ) {
			fullScreenApi.prefix = browserPrefixes[i];
			if (typeof document[fullScreenApi.prefix + 'CancelFullScreen' ] != 'undefined' ) {
				fullScreenApi.supportsFullScreen = true;
				break;
			}
		}
	}
	// update methods to do something useful
	if (fullScreenApi.supportsFullScreen) {
		fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';
		fullScreenApi.isFullScreen = function() {
			switch (this.prefix) {
				case '':
					return document.fullScreen;
				case 'webkit':
					return document.webkitIsFullScreen;
				default:
					return document[this.prefix + 'FullScreen'];
			}
		}
		fullScreenApi.requestFullScreen = function(el) {
			return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
		}
		fullScreenApi.cancelFullScreen = function(el) {
			return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
		}
	}
	// jQuery plugin
	if (typeof jQuery != 'undefined') {
		jQuery.fn.requestFullScreen = function() {
			return this.each(function() {
				if (fullScreenApi.supportsFullScreen) {
					fullScreenApi.requestFullScreen(this);
				}
			});
		};
	}
	// export api
	window.fullScreenApi = fullScreenApi;
})();

This creates an object called fullScreenApi with a boolean property supportsFullScreen and some methods that allow you to do something more universal. Here’s an example usage:

if (fullScreenApi.supportsFullScreen) {
	myButton.addEventListener('click', function() {
		fullScreenApi.requestFullScreen(someElement);
	}, true);
}

You can see it in action below:
Simple Demo Video Demo

Issues and Updates

Since this post, there are some additional things worth mentioning

  • Security concerns – Browser vendors are well aware of the potential security issues with fullscreen. For example, a malicious site could show a full screen Windows or Mac login window and steal a password. That’s why they are disabling keyboard support by default and only enabling by explicitly asking.
  • Internet Explorer supportI have an email from a IE team member saying they are discussing it, but have not made any decisions. As of now, IE10 will not implement the FullScreen API, the IE team has not yet decided if they will implement the FullScreen API.
  • FullscreenEnabled vs. IsFullScreen – The W3C includes the very helpful fullscreenEnabled flag to let your code know if you can use the API, but strangely the W3C does not include an isFullscreen flag. WebKit on the other hand has webkitIsFullScreen, but does not have a webkitFullScreenEnabled equivalent property. Mozilla helpfully includes both.
  • FullScreenChanged event – The W3C and Webkit fire the fullscreenchanged event on the element going fullscreen, but Mozilla fires the event on the document object.

74 thoughts on “Native Fullscreen JavaScript API (plus jQuery plugin)

  1. It doesn’t appear that the simple demo works while testing in Firefox Nightly. Is this a feature that needs to be turned on? Feature detect was successful however.

    1. Make sure you’ve enabled it in about:config.
      Just search for “full-screen-api.enabled” and set it to true! 🙂
      (btw the labels in this for are very confusingly positioned. I see them below the actual field and with plenty of room between)

  2. The FullScreen option is very important in a serious JavaScript application, especially something like the artificial intelligence for Microsoft Internet Explorer, which in the User Manual simply advises users to press the “function key F11 at the top of your keyboard to toggle or alternate between a full-screen display and the normal screen of Microsoft Internet Explorer (MSIE).”

  3. Nice article, thought you’d appreciate some updates:
    1) document.fullscreen has been depricated in the W3C proposal due to similarity to document.fullscreenElement
    See: http://dvcs.w3.org/hg/fullscreen/rev/134dab3ac127
    Note: document.fullscreen was a boolean, whereas document.fullscreenElement is either a string (current fullscreen element) or undefined. This has no effect for the time being, as the draft is not implemented, however it will effect the future.
    2) It is also worth mentioning the “@media (view-type: fullscreen)” draft. Currently supported in only Opera (I think).
    See: http://www.w3.org/TR/view-mode/#the–view-mode–media-feature
    And: http://www.opera.com/docs/specs/presto27/css/viewmode/
    This, I think, allows you to style any element for when the document is in fullscreen mode. It also allows you to take advantage of when the user hits F11.
    e.g:
    //styles
    @media (view-type: fullscreen) {
    div#videoContainer {
    //fullscreen-styles
    }
    video {
    //fullscreen-styles
    }
    }

    1. Thanks Matt! I’m not sure I understand why W3C doesn’t have a fullscreen state flag like Webkit and Mozilla. Hopefully, it’ll become clearer as they work out the kinks.

    2. The ability to specify fullscreen styling via @media is exactly what’s needed, thanks for making us aware of it – and it would be utter madness if W3C didn’t incorporate it!

    1. Thanks David. I emailed Anne, and she said they were still working on it. But to me it still seems strange to be so out of sync from the Mozilla proposal and Apple implementation since those have been out so long…

  4. Document.fullScreenEnabled also returns false if any of the document’s containing iframes don’t have the “allowfullscreen” attribute present. You can use this in custom video controls embedded in an iframe to determine whether it’s worthwhile showing the full-screen button in your controls. And in Firefox at least it also returns false if there’s a windowed plugin present in any of the full-screen documents.
    The “fullscreendenied” event has been named to “fullscreenerror” in the W3C spec, and support for it as the “mozfullscreenerror” event landed in Firefox yesterday, and will appear in nightly builds tomorrow.

  5. So i’m a bit confused, can’t I just do a simple one liner in jquery to get this to put the document into fullscreen(same as if I pressed f-11 in Chrome?
    $(‘.fullScreenButton’).click(function{
    document.webkitRequestFullScreen();
    });
    Is it possible to do it in a nice little compact way like this, instead of the plugin you made?

    1. Yes, you could do a one-liner, but right now the browsers are all using vendor prefixes and the API is set to change which means your code might not be future proof if you don’t wrap it in something that can mitigate the changes.

  6. Would be nice to add Fullscreen detection to Modernizr, is anyone already on the case or shall I suggest it?

  7. “Windows 8 Metro style Internet Explorer is always full screen … and as before, F11 enters full screen mode in desktop versions of IE.”
    Not really helpful when you need to go full-screen from an embedded source like an iframe, as we do for our embedded html video player at Vimeo. Guess IE users will continue getting the shaft (ie. have to use Flash, which is not even an option in Metro).

  8. and what about opera? does it suport fullscreen?
    we could simulate a F11 keypress on IE or it don’t work?

  9. Thanks for this nice script ! It’s perfect for jquery slideshow, but what about normal pages ? I can’t get a scrollbar there, it’s impossible to scrolldown inside a long div… do you know why ? Thanks in advance !!

  10. Pretty nice. I don´t think that many users will actually click on “fullscreen” unless they wanne watch a movie or really hd images… Therefor it´s perfect. Thanks for sharing!

  11. Great article! Full those who are interested in keyboard support under fullscreen mode, in webkit you can do
    webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT), then you have full keyboard support.
    For firefox, by default, the keyboard is allowed, but most key will also initiate the “press ESC to exit full screen” popup (which is rather huge), I didn’t find a way to disable that.

  12. Hello, I have met a question :
    I want the web page to be initialized fullscreen, So I use the following code :
    fullScreenApi.requestFullScreen(document.getElementById(‘id’));
    But it didn’t go as expected !
    Is there any solutions , or there was bugs in my code ? Thanks !

  13. Worth noting, by the way – to use the API inside of an iframe, you currently need to slap on all the vendor prefixes in the iframe tag attributes too, i e something like: <iframe src=”url” allowfullscreen mozallowfullscreen webkitallowfullscreen oallowfullscreen msallowfullscreen> (to be sure all browsers will allow the API, if / once they implement it).

  14. Having implemented this API there are couple of things I’ve noticed that aren’t well documented elsewhere. This may not pertain to every implementation but it did to mine and may help some folks:
    1. Loading a new page in Firefox will take you out of fullscreen unless you’re using asynchronous JavaScript to load new images or what have you. In the site I was constructing this wasn’t really feasible so I removed the fullscreen ability from Firefox which to me was a minor issue as it’s an ‘added bonus’ not core functionality. However in Safari / Chrome it will remain in fullscreen when you navigate to new pages.
    2. If you’re using fullscreen to navigate to new pages in Safari / Chrome there is no way to indicate that you’re still in fullscreen. It reverts back to thinking that you’re not. Which means calling a ‘cancelFullScreen’ request using a button will not work. My workaround for this was to attach a ‘requestFullScreen’ event prior to my ‘cancelFullScreen’ event on my button function. May not be elegant, but it works.
    3. Further along the same lines having navigated away from the original fullscreen state I created a JavaScript function detecting an ESC being pressed which reverts properly to the previous non-fullscreen state.
    If I’m mistaken, then please let me know and thanks for the hard work Mr. Dyer.

  15. Hi All,
    That full screen is cool, but i want full screen for attr body not attr (div).
    When i load complete page then full screen page, please help me!

  16. Hello
    the API is great but i need add extra JS code when the user exit the full screen by press at ESC, ino your code i should insert it here
    fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
    if (fullScreenApi.isFullScreen()) {
    fsStatus.innerHTML = ‘Whoa, you went fullscreen’;
    } else {
    fsStatus.innerHTML = ‘Back to normal’;
    //extra JS code
    }
    }, true);
    its works fine at chrome but not at FF, hope can help me if i miss something
    thanks again

  17. Hey Guys. i am trying to implement the API. but not Success. i am quite new to JS. here what i am doing.
    copying the code into JS file working very well.
    when the DOM is ready i am implementing this code.
    try{switchToFULLScreen();}catch(E){alert(E);}//not exception is show…
    }
    function switchToFULLScreen()
    {
    var element = document.getElementById(‘rs2010’);//the element is visible… exist..
    alert(fullScreenApi.isFullScreen());//returning false;
    alert(fullScreenApi.supportsFullScreen);//return true;
    alert(fullScreenApi.requestFullScreen(element));//undefinded.
    alert(fullScreenApi.isFullScreen());//returning false;
    }
    i am using Google Chrome. 18.0 any help is very appreciate. please any suggest to my code chiperortiz@hotmail.com or throught this page. God Bless.

  18. Hey Guys. Is Working now. but i have a question… i need to resize the div when the fullscreen is toggling. the following code i am using.
    function switchToFULLScreen()
    {
    var element = document.getElementById(‘outerdiv’);
    $(‘.big_center’).css(‘height’,’550%’);
    fullScreenApi.requestFullScreen(element);
    }
    function switchToNormalScreen()
    {
    var element = document.getElementById(‘outerdiv’);
    $(‘.big_center’).css(‘height’,’446.9%’); }
    Is Working well. but when i am doing manually. but i want to detect the F11 pressing to resize my div that’s is possible or not. thanks a lot.

  19. In Chrome it works fine. But it always leaves full screen mode in FF once you click on another link. Looks like the script does not recognize the current status of full screen mode enabled.

  20. Hi! This works great, thanks. I’ve used the code from the simple demo but I can’t figure out how to create a toggle function which would turn fullscreen on and off when a button is clicked. The button would be always visible on the screen and only change appearance via class name toggled by the same function.
    If anyone would be so kind to modify the code appropriately, that would be fab!
    var fsButton = document.getElementById(‘fsbutton’),
    fsElement = document.getElementById(‘specialstuff’),
    fsStatus = document.getElementById(‘fsstatus’);
    if (window.fullScreenApi.supportsFullScreen) {
    fsStatus.innerHTML = ‘YES: Your browser supports FullScreen’;
    fsStatus.className = ‘fullScreenSupported’;
    // handle button click
    fsButton.addEventListener(‘click’, function() {
    window.fullScreenApi.requestFullScreen(fsElement);
    }, true);
    fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
    if (fullScreenApi.isFullScreen()) {
    fsStatus.innerHTML = ‘Whoa, you went fullscreen’;
    } else {
    fsStatus.innerHTML = ‘Back to normal’;
    }
    }, true);
    } else {
    fsStatus.innerHTML = ‘SORRY: Your browser does not support FullScreen’;
    }

  21. Do you know why the fullscreen API would generate a black background in Safari, when there is no black background set?

  22. Hi there,
    great piece of code thanks for sharing!
    Problem is in FF 17.01 it throws an error on line 50 whether I implement it using straight js or use the jquery plugin:
    TypeError: el[(this.prefix + “RequestFullScreen”)] is not a function
    [Break On This Error]
    …(this.prefix === ”) ? el.requestFullScreen() : el[this.prefix + ‘RequestFullScr…
    This is how I am calling it, from within the click handler of a button:
    var fsElement = $(“body”);
    if (window.fullScreenApi.supportsFullScreen) {
    alert(‘YES: Your browser supports FullScreen’);
    window.fullScreenApi.requestFullScreen(fsElement);
    fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
    if (fullScreenApi.isFullScreen()) {
    alert(“in full screen”);
    } else {
    alert(“back to normal”);
    }
    }, true);
    } else {
    alert(“not supported”);
    }
    Any thoughts or ideas welcome…
    Cheers!
    Jamie

  23. Hi there just wanted to give you a quick heads up. The text in your content seem to bbe running off the screen in Ie.
    I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post
    to let yyou know. Thee layout look greeat though! Hope you get
    the problem resolved soon. Many thanks
    Feel frtee to visit mmy hpmepage – servizi fotografici milano

  24. Good day! I could have sworn I’ve been to this website before but after checking through
    some of the post I realized it’s new to me.
    Anyways, I’m definitely glad I found it and
    I’ll be book-marking and checking back often!

Comments are closed.