Native Fullscreen JavaScript API (plus jQuery plugin)

October 20, 2011 | JavaScript | 33 Comments

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

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.

33 Responses to “Native Fullscreen JavaScript API (plus jQuery plugin)”

  1. LockeVN says:

    End-user Chrome version 15.0.874.102 m is now support FullScreen API, and this code works!

  2. [...] Native Fullscreen JavaScript API (plus jQuery plugin); [...]

  3. Jordan says:

    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.

    • johndyer says:

      I’ve only tested on a Mac, but my Firefox Nightly is still working. What does yours do?

    • Daniel Johansson says:

      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)

  4. Mentifex says:

    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).”

  5. [...] 2, 2011 Just a quick note for you. If you’re into web app development, this might be an interesting read. It’s on using JavaScript to make pages fullscreen, hiding the browser chrome and making your [...]

  6. 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
    }
    }

    • johndyer says:

      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.

    • Marcus Tucker says:

      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!

  7. David says:

    It’s worth noting that the specification was not proposed with differences out of the blue. That draft of the spec was discussed at the WHATWG with other browser vendors. It’s likely still under development too. See the many threads here.

    http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2011-October/thread.html

  8. Chris Pearce says:

    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.

  9. Nick says:

    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?

    • johndyer says:

      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.

  10. [...] Your Content Do the Talking: Fullscreen API 2. 大部分代码引用这篇文章:Native Fullscreen JavaScript API (plus jQuery plugin) 3. 历史和讨论:Fullscreen HTML5 video 4. 标准与厂商对比:W3C Draft: Fullscreen [...]

  11. [...] I hope you enjoyed my post. Some facts and code examples I've taken from another blog, so I would like to add this as a source. [...]

  12. Marcus Tucker says:

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

  13. Marc says:

    How does this handle dual screens? Is it possible to use two or three screens simultaneously?

  14. “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).

  15. Marco Campos says:

    and what about opera? does it suport fullscreen?

    we could simulate a F11 keypress on IE or it don’t work?

  16. ariok says:

    it’s possible to default chrome into fullscreen every open it?

  17. [...] from my program? Answer (Unmark) 12/15/11 1:45 PM as a reply to ivanov -void. Hi,maybe this helps [...]

  18. Knotschi says:

    in line 66 you have : fullScreenApi.requestFullScreen(el);
    that have to be: fullScreenApi.requestFullScreen(el[0]);

    greets

Leave a Reply

Fork me on GitHub

Social Widgets powered by AB-WebLog.com.