Full screen with javascript

Guide to the Fullscreen API

This article demonstrates how to use the Fullscreen API to place a given element into fullscreen mode, as well as how to detect when the browser enters or exits fullscreen mode.

Activating fullscreen mode

Given an element that you’d like to present in fullscreen mode (such as a , for example), you can present it in fullscreen mode by calling its requestFullscreen() method.

video controls id="myvideo"> source src="somevideo.webm">source> source src="somevideo.mp4">source> video> 

We can put that video into fullscreen mode as follows:

const elem = document.getElementById("myvideo"); if (elem.requestFullscreen)  elem.requestFullscreen(); > 

This code checks for the existence of the requestFullscreen() method before calling it.

Presentation differences

It’s worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: » width: 100%; height: 100% «. WebKit doesn’t do this; instead, it centers the fullscreen element at the same size in a screen that’s otherwise black. To get the same fullscreen behavior in WebKit, you need to add your own » width: 100%; height: 100%; » CSS rules to the element yourself:

#myvideo:-webkit-full-screen  width: 100%; height: 100%; > 

On the other hand, if you’re trying to emulate WebKit’s behavior on Gecko, you need to place the element you want to present inside another element, which you’ll make fullscreen instead, and use CSS rules to adjust the inner element to match the appearance you want.

Notification

When fullscreen mode is successfully engaged, the document which contains the element receives a fullscreenchange event. When fullscreen mode is exited, the document again receives a fullscreenchange event. Note that the fullscreenchange event doesn’t provide any information itself as to whether the document is entering or exiting fullscreen mode, but if the document has a non null fullscreenElement , you know you’re in fullscreen mode.

When a fullscreen request fails

It’s not guaranteed that you’ll be able to switch into fullscreen mode. For example, elements have the allowfullscreen attribute in order to opt-in to allowing their content to be displayed in fullscreen mode. In addition, certain kinds of content, such as windowed plug-ins, cannot be presented in fullscreen mode. Attempting to put an element which can’t be displayed in fullscreen mode (or the parent or descendant of such an element) won’t work. Instead, the element which requested fullscreen will receive a mozfullscreenerror event. When a fullscreen request fails, Firefox will log an error message to the Web Console explaining why the request failed. In Chrome and newer versions of Opera however, no such warning is generated.

Note: Fullscreen requests need to be called from within an event handler or otherwise they will be denied.

Getting out of full screen mode

The user always has the ability to exit fullscreen mode of their own accord; see Things your users want to know. You can also do so programmatically by calling the Document.exitFullscreen() method.

Other information

The Document provides some additional information that can be useful when developing fullscreen web applications:

The fullscreenElement property tells you the Element that’s currently being displayed fullscreen. If this is non-null, the document (or shadow DOM) is in fullscreen mode. If this is null, the document (or shadow DOM) is not in fullscreen mode.

The fullscreenEnabled property tells you whether or not the document is currently in a state that would allow fullscreen mode to be requested.

Viewport scaling in mobile browsers

Some mobile browsers while in fullscreen mode ignore viewport meta-tag settings and block user scaling; for example: a «pinch to zoom» gesture may not work on a page presented in fullscreen mode — even if, when not in fullscreen mode, the page can be scaled using pinch to zoom.

Things your users want to know

You’ll want to be sure to let your users know that they can press the Esc key (or F11 ) to exit fullscreen mode.

In addition, navigating to another page, changing tabs, or switching to another application (using, for example, Alt — Tab ) while in fullscreen mode exits fullscreen mode as well.

Example

In this example, a video is presented in a web page. Pressing the Return or 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.

.addEventListener( "keydown", (e) =>  if (e.keyCode === 13)  toggleFullScreen(); > >, false, ); 

Toggling fullscreen mode

This code is called when the user hits the Enter key, as seen above.

function toggleFullScreen()  if (!document.fullscreenElement)  document.documentElement.requestFullscreen(); > else if (document.exitFullscreen)  document.exitFullscreen(); > > 

This starts by looking at the value of the fullscreenElement attribute on the document . If it’s null , the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling element.requestFullscreen() .

If fullscreen mode is already active ( fullscreenElement is non- null ), we call document.exitFullscreen() .

Prefixing

For the moment not all browsers are implementing the unprefixed version of the API (for vendor agnostic access to the Fullscreen API you can use Fscreen). Here is the table summarizing the prefixes and name differences between them:

Standard WebKit (Safari) / Blink (Chrome & Opera) / Edge Gecko (Firefox) Internet Explorer
Document.fullscreen Deprecated webkitIsFullScreen mozFullScreen
Document.fullscreenEnabled webkitFullscreenEnabled mozFullScreenEnabled msFullscreenEnabled
Document.fullscreenElement webkitFullscreenElement mozFullScreenElement msFullscreenElement
Document.exitFullscreen() webkitExitFullscreen() mozCancelFullScreen() msExitFullscreen()
Element.requestFullscreen() webkitRequestFullscreen() mozRequestFullScreen() msRequestFullscreen()

Specifications

Browser compatibility

api.Document.fullscreenEnabled

BCD tables only load in the browser

api.Document.fullscreen

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How TO — Fullscreen

Learn how to make a fullscreen window with JavaScript.

Fullscreen Window

How to use JavaScript to view an element in fullscreen mode.

Click on the button to open the video in fullscreen mode:

Your browser does not support the video tag.

Fullscreen Video

To open an element in fullscreen, we use the element.requestFullscreen() method:

Example

/* When the openFullscreen() function is executed, open the video in fullscreen.
Note that we must include prefixes for different browsers, as they don’t support the requestFullscreen method yet */
function openFullscreen() if (elem.requestFullscreen) elem.requestFullscreen();
> else if (elem.webkitRequestFullscreen) < /* Safari */
elem.webkitRequestFullscreen();
> else if (elem.msRequestFullscreen) < /* IE11 */
elem.msRequestFullscreen();
>
>

Fullscreen Document

To open the whole page in fullscreen, use the document.documentElement instead of document.getElementById(«element«) . In this example, we also use a close function to close the fullscreen:

Example

/* View in fullscreen */
function openFullscreen() if (elem.requestFullscreen) elem.requestFullscreen();
> else if (elem.webkitRequestFullscreen) < /* Safari */
elem.webkitRequestFullscreen();
> else if (elem.msRequestFullscreen) < /* IE11 */
elem.msRequestFullscreen();
>
>

/* Close fullscreen */
function closeFullscreen() if (document.exitFullscreen) document.exitFullscreen();
> else if (document.webkitExitFullscreen) < /* Safari */
document.webkitExitFullscreen();
> else if (document.msExitFullscreen) < /* IE11 */
document.msExitFullscreen();
>
>

You can also use CSS to style the page when it is in fullscreen mode:

Example

/* Safari */
:-webkit-full-screen background-color: yellow;
>

/* IE11 */
:-ms-fullscreen background-color: yellow;
>

/* Standard syntax */
:fullscreen background-color: yellow;
>

Источник

Как использовать Fullscreen API

В комплекте с HTML5 появилось большое количество нового API. Одним из них является Fullscreen API, которое предоставляет нативный способ для браузера, позволяющий отобразить веб-страницу в полноэкранном режиме для пользователя.
А еще хорошо то, что Fullscreen API является очень простым в использовании.

Методы

Методы, входящие в состав Fullscreen API

Согласно стандарту W3C название некоторых методов было изменено, но старые названия продолжают работать.

Document.getElementById("myCanvas").requestFullscreen() 
Document.fullscreenEnabled 
Document.fullScreenElement 

Возвращает элемент, который в настоящее время находится в полноэкранном режиме.
Обратите внимание, что это стандартные методы. Для того, что бы они работали во всех браузерах, нам необходимо использовать префиксы.

Поддерживаемые браузеры
  • Chrome
  • Firefox
  • Safari
  • Opera Next
  • Opera (начиная с версии 12.10)
  • Internet Explorer (начиная с версии 11)

Более подробная информация по поддержке Fullscreen API современными браузерами доступна по ссылке.

Будет полезным скрипт, позволяющий автоматически определять поддержку браузером Fullscreen API и в случае необходимости добавляет необходимый префикс к методам Fullscreen API.

Запуск полноэкранного режима

Сначала мы должны выяснить, какой метод распознает наш браузер. Для этого мы создадим функцию, которая будет проверять поддержку метода и вызовет рабочий метод:

function fullScreen(element) < if(element.requestFullscreen) < element.requestFullscreen(); >else if(element.webkitrequestFullscreen) < element.webkitRequestFullscreen(); >else if(element.mozRequestFullscreen) < element.mozRequestFullScreen(); >> 

Если любой из requestFullscreen методов возвращают истинное значении, то вызывается тот метод, который поддерживается конкретным браузером и использует псевдокласс с его префикском.

После этого нужно вызвать функцию для полноэкранного режима:

//для всей страницы var html = document.documentElement; fullScreen(html); 
// Для конкретного элемента на странице var canvas = document.getElementById('mycanvas'); fullScreen(canvas); 

Результатом будет запрос пользователю с просьбой разрешить переход в полноэкранный режим, если пользователь разрешит переход, то все панели инструментов в браузере исчезнут, и на всем экране будет веб-страница или один элемент.

Отмена полноэкранного режима

Этот метод также требует префиксы, поэтому мы будем использовать ту же идею для проверки поддержки методов браузерами. Создадим функцию, которая будет определять, какой префикс мы должны использовать в зависимости от браузера пользователя.

Этот метод не требует никаких параметров, поскольку в отличие от метода requestFullscreen он всегда относится ко всему документу.

function fullScreenCancel() < if(document.requestFullscreen) < document.requestFullscreen(); >else if(document.webkitRequestFullscreen ) < document.webkitRequestFullscreen(); >else if(document.mozRequestFullscreen) < document.mozRequestFullScreen(); >> 
//отменяет полноэкранный режим fullScreenCancel(); 

CSS псевдоклассы

Он может быть использован для задания стиля любых элементов на веб-странице, когда страница или элемент находится в полноэкранном режиме. Данный псевдокласс может пригодиться для задания размера элементов страницы, потому что в полноэкранном режиме происходит увеличение и самого рабочего пространства браузера.

:-webkit-full-screen :-moz-full-screen :full-screen /*изменения одного элемента img*/ :-webkit-full-screen img < width: 100%; height: 100%; >:-moz-full-screen img

Учтите, что нельзя отделять префиксы запятыми, потому что браузер не сможет распознать их:

/* Это не будет работать */ :-webkit-full-screen img,:-moz-full-screen img

Для того, чтобы стили применялись правильно, вы должны поместить каждый псевдокласс с префиксом браузера в своем собственном блоке.

Заключение

Этот JavaScript API является одним из наименее известных из поставляемых с HTML5, но это эффективный и простой в реализации метод, позволяющий сфокусировать внимание пользователя на одном элементе, что особенно полезно для видео, изображений и игр.

Источник

Читайте также:  Python embedded install tkinter
Оцените статью