Как использовать Fullscreen API
В комплекте с HTML5 появилось большое количество нового API. Одним из них является Fullscreen API, которое предоставляет нативный способ для браузера, позволяющий отобразить веб-страницу в полноэкранном режиме для пользователя.
А еще хорошо то, что Fullscreen API является очень простым в использовании.
Методы
Методы, входящие в состав Fullscreen API
Согласно стандарту W3C название некоторых методов было изменено, но старые названия продолжают работать.
Этот метод позволяет одному элементу перейти в полноэкранный режим.
Выполнение этого кода приведет к тому, что canvas с ID «myCanvas» перейдет в полноэкранный режим.
новое название атрибута:
Отменяет полноэкранный режим.
новое название атрибута:
Возвращает значение «истина», если пользователь находится в полноэкранном режиме.
Возвращает элемент, который в настоящее время находится в полноэкранном режиме.
Обратите внимание, что это стандартные методы. Для того, что бы они работали во всех браузерах, нам необходимо использовать префиксы.
Поддерживаемые браузеры
- Chrome
- Firefox
- Safari
- Opera Next
- Opera (начиная с версии 12.10)
- Internet Explorer (начиная с версии 11)
Более подробная информация по поддержке Fullscreen API современными браузерами доступна по ссылке.
Будет полезным скрипт, позволяющий автоматически определять поддержку браузером Fullscreen API и в случае необходимости добавляет необходимый префикс к методам Fullscreen API.
Запуск полноэкранного режима
Сначала мы должны выяснить, какой метод распознает наш браузер. Для этого мы создадим функцию, которая будет проверять поддержку метода и вызовет рабочий метод:
Если любой из requestFullscreen методов возвращают истинное значении, то вызывается тот метод, который поддерживается конкретным браузером и использует псевдокласс с его префикском.
После этого нужно вызвать функцию для полноэкранного режима:
Результатом будет запрос пользователю с просьбой разрешить переход в полноэкранный режим, если пользователь разрешит переход, то все панели инструментов в браузере исчезнут, и на всем экране будет веб-страница или один элемент.
Отмена полноэкранного режима
Этот метод также требует префиксы, поэтому мы будем использовать ту же идею для проверки поддержки методов браузерами. Создадим функцию, которая будет определять, какой префикс мы должны использовать в зависимости от браузера пользователя.
Этот метод не требует никаких параметров, поскольку в отличие от метода requestFullscreen он всегда относится ко всему документу.
CSS псевдоклассы
В комплекте с этим JavaScript API пришли и CSS псевдоклассы
Он может быть использован для задания стиля любых элементов на веб-странице, когда страница или элемент находится в полноэкранном режиме. Данный псевдокласс может пригодиться для задания размера элементов страницы, потому что в полноэкранном режиме происходит увеличение и самого рабочего пространства браузера.
Учтите, что нельзя отделять префиксы запятыми, потому что браузер не сможет распознать их:
Для того, чтобы стили применялись правильно, вы должны поместить каждый псевдокласс с префиксом браузера в своем собственном блоке.
Fullscreen API
The Fullscreen API adds methods to present a specific Element (and its descendants) in fullscreen mode, and to exit fullscreen mode once it is no longer needed. This makes it possible to present desired content—such as an online game—using the user’s entire screen, removing all browser user interface elements and other applications from the screen until fullscreen mode is shut off.
See the article Guide to the Fullscreen API for details on how to use the API.
Note: Support for this API varies somewhat across browsers, with many requiring vendor prefixes and/or not implementing the latest specification. See the Browser compatibility section below for details on support for this API. You may wish to consider using a library such as Fscreen for vendor agnostic access to the Fullscreen API.
Interfaces
The Fullscreen API has no interfaces of its own. Instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide fullscreen functionality. These are listed in the following sections.
Instance methods
The Fullscreen API adds methods to the Document and Element interfaces to allow turning off and on fullscreen mode.
Instance methods on the Document interface
Requests that the user agent switch from fullscreen mode back to windowed mode. Returns a Promise which is resolved once fullscreen mode has been completely shut off.
Instance methods on the Element interface
Asks the user agent to place the specified element (and, by extension, its descendants) into fullscreen mode, removing all of the browser’s UI elements as well as all other applications from the screen. Returns a Promise which is resolved once fullscreen mode has been activated.
Instance properties
The Document interface provides properties that can be used to determine if fullscreen mode is supported and available, and if fullscreen mode is currently active, which element is using the screen.
The fullscreenElement property tells you the Element that’s currently being displayed in fullscreen mode on the DOM (or shadow DOM). If this is null , the document (or shadow DOM) is not in fullscreen mode.
The fullscreenEnabled property tells you whether or not it is possible to engage fullscreen mode. This is false if fullscreen mode is not available for any reason (such as the «fullscreen» feature not being allowed, or fullscreen mode not being supported).
Obsolete properties
A Boolean value which is true if the document has an element currently being displayed in fullscreen mode; otherwise, this returns false .
Note: Use the fullscreenElement property on the Document or ShadowRoot instead; if it’s not null , then it’s an Element currently being displayed in fullscreen mode.
Events
The Fullscreen API defines two events which can be used to detect when fullscreen mode is turned on and off, as well as when errors occur during the process of changing between fullscreen and windowed modes.
Sent to an Element when it transitions into or out of fullscreen mode.
Sent to an Element if an error occurs while attempting to switch it into or out of fullscreen mode.
Controlling access
The availability of fullscreen mode can be controlled using a Permissions Policy. The fullscreen mode feature is identified by the string «fullscreen» , with a default allowlist value of «self» , meaning that fullscreen mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document.
Usage notes
Users can choose to exit fullscreen mode by pressing the ESC (or F11 ) key, rather than waiting for the site or app to programmatically do so. Make sure you provide, somewhere in your user interface, appropriate user interface elements that inform the user that this option is available to them.
Note: Navigating to another page, changing tabs, or switching to another application using any application switcher (or Alt — Tab ) will likewise exit fullscreen mode.
Examples
Simple fullscreen usage
In this example, a video is presented in a web page. Pressing the Enter key lets the user toggle between windowed and fullscreen presentation of the video.
Watching for the Enter key
When the page is loaded, this code is run to set up an event listener to watch for the Enter key.
Toggling fullscreen mode
This code is called by the event handler above when the user hits the Enter key.
This starts by looking at the value of the document ‘s fullscreenElement attribute. In a real-world deployment, at this time, you’ll want to check for prefixed versions of this ( mozFullScreenElement , msFullscreenElement , or webkitFullscreenElement , for example). If the value is null , the document is currently in windowed mode, so we need to switch to fullscreen mode; otherwise, it’s the element that’s currently in fullscreen mode. Switching to fullscreen mode is done by calling Element.requestFullscreen() on the <video> element.
If fullscreen mode is already active ( fullscreenElement is not null ), we call exitFullscreen() on the document to shut off fullscreen mode.
How to Make the Window Full Screen with Javascript
![]()
Making an element in the page to go to a full screen window can be achieved using Javascript Fullscreen API.
Quick Sample Code
Tutorial in Detail
Full-screen can be activated for the whole browser window by pressing the F11 key. It can be exited by pressing the Esc button.
It is also possible to make a specific element in the page to enter and exit full-screen mode programmatically using Javascript Fullscreen API.
This tutorial discusses the methods, properties and events available in the Fullscreen API.
Example of Fullscreen API
Javascript FullScreen API
The Fullscreen API provides functions to enter and exit full-screen mode, as well as an event to detect full-screen state change.
Also specific CSS can be applied to an element that goes in full-screen mode.
- Element .requestFullscreen function can make an element go to full-screen mode.
- document.exitFullscreen function can exit full-screen.
- document.fullscreenElement property holds the element which is currenly in full-screen.
- fullscreenchange event can detect when element enters and exits full-screen mode.
- fullscreenerror event can detect errors when entering and exiting full-screen mode.
- document.fullscreenEnabled property tells whether full-screen can be enabled in the current page or not.
- :fullscreen and ::backdrop CSS properties handle styling when element enters full-screen.
Going Into Full-Screen
We can request an element in the page to go into full-screen using the Element.requestFullscreen function. Element refers to the DOM element.
This function is asynchronous, and returns a Promise. The Promise is resolved when the element successfully enters full-screen mode. The Promise is rejected if an error occurs.
By default, the browser navigation UI will be hidden in full-screen mode. However it is possible to keep the navigation UI in fullscreen mode also, by using the navigationUI parameter.
navigationUI parameter can have 3 values :
- «hide» : Hide the browser navigation UI
- «show» : Show the browser navigation UI
- «auto» : The default behaviour applied by browser
Exiting Full-Screen
We can exit full screen using the document.exitFullscreen function. Note that this function is not called on the element, but rather the document object.
This also is an asynchronous function, and returns a Promise. The Promise is resolved when the element exits full-screen mode and rejected in case of an error.
Check Which Element is in Full-Screen
We can assign many elements in your page to use full-screen mode. However we might want to know which element is currently being displayed in full-screen mode. document.fullscreenElement is a read-only property that returns the DOM Node of that element.
If the page is not in full-screen mode, null is returned.
Check Whether Full-Screen Activated Currently
To find out whether full-screen is currently activated, we can find the element which is in full-screen. If such an element is found, it means full-screen is activated, otherwise full-screen is deactivated.
Event to Detect Full-Screen State Changes
fullscreenchange event detects change in full-screen mode. This event can be applied to the document or to specific elements.
Check Whether Full-Screen is Allowed in the Page
Sometimes due to restrictions placed, it may not be possible to enter full-screen mode for the current page. The document.fullscreenEnabled property returns a boolean true or false indicating whether full-screen is available or not.
CSS for Elements in Full-Screen
When an element enters full-screen mode, specific CSS styles can be applied to them.
The :fullscreen CSS pseudo class can be used to style elements when they enter full-screen mode.
When an element enters fullscreen, it may have a default black backdrop. The ::backdrop CSS pseudo-element can be used to customize element’s backdrop styles.
Browser Compatibility for Full-Screen API
Javascript Full-screen API is available for all major browsers, with some exceptions :
Detect full screen using Javascript

Why would you want to detect if the browser is full screen? In my case, I made a dashboard that is configurable with different controls, but it is expected to be in “production” when the browser goes full screen and by then the controls would just be clutter and should be hidden. I found it to be not-as-simple-as-you-may-think.
Even with two different approaches, I have something working, but it is not optimal. My approach – when I detect the browser is full screen I add the class fullscreen to the <body> -element otherwise the class should be removed from the body-element.
First try: Compare the dimensions of the window and the screen.
The Javascript object screen can tell you about the visitors screen – things such as dimensions. So ask for screen.height and you may get 1200 back or ask for screen.availHeight and get 1175 back. availHeight tells you how much is available if you subtract the height of menus on the Mac or the Taskbar in Windows. Compare this to the height of say the window-object ( window.innerHeight ) and you will know if the size of the window is equal to (or close to being) as tall as the screen and thereby you know if the window is full screen (or almost).
Why this is not good enough
One assumption is that a visitor has only one screen. As i write this, I work on a laptop connected to one and sometimes two external monitors. Dragging my browser from one screen to another screen will rarely mean a new value for screen.height even though the number of pixels differ between screens. This may change in the future, but not as I am writing this.
Another assumption that breaks this approach surfaces if you try to zoom in or out in your browser using CTRL/CMD with plus or minus. window.innerHeight increases as you zoom out – so it will no longer represent the number of physical pixels and comparing it to screen.height is suddenly like comparing apples and oranges. You had better stick to window.outerHeight , BUT if you are not sure that screen.height actually represents the height of the screen showing the browser, it seems this approach was a bad idea from the beginning.
Second try: Detect if the use requested full screen using a button
So I added a Show full screen-button to the screen with a click-handler like:
That way most browsers should go to full screen, when the button is clicked. I could just add the fullscreen class to the <body> -element directly here, but I would really like to detect when the browser leaves full-screen again, to remove the class and show the controls again, so this function is called on every window.onresize -event:
The only thing I need is to implement the isFullScreen() -function. Browser api’s are available – implemented somewhat differently across browsers. Safari has document.webkitCurrentFullScreenElement which resolves to the element that initiated the full screen mode (if the browser is in fullscreen mode). For cross-browser compatibility, this would be sufficient:
Is there a snag? Of course there is. In order for the code above to return true, the browser window MUST be put in full-screen mode by an element on the page. If the browser was put in full-screen mode from the browser menu or from a command-line argument when the browser was started, there is no document.webkitCurrentFullScreenElement and the function will return false and my controls are still visible on the page.
Third try: Look at window position
I stumbled across this post on Stackoverflow with the bold intro: This works on all new browsers. Being desparate i gave it a go:
Crossing fingers… and getting close. In Google Chrome, both the button on the page and the menu action makes this function return true. The menu action to return from full-screen mode however seems to trigger no window.resize-event, hence the controls remain hidden when I leave full-screen mode from the browser menu. Digging further into this, it seems the resize is triggered, but window.ScreenTop and/or window.screenY are. updated with a delay. So by adding a one second delay after the resize-event is triggered, before checking if the browser is full-screen with the function above everything seems to work!
So the code to it’s full extend ended up as:
Timing was tested on MacOS with Safari, Chrome and Firefox – tried lowering it to 100ms, but Firefox did not finish animating/updating the window.screenTop and window.screenY so a 300ms delay seems to do the trick.
One thing i can live with for now: The check also triggers when the window is maximized – not just full-screen.
Maybe I should just show the controls if there is mouse or keyboard activity and hide them after 30 seconds of inactivity?