Simple wrapper for cross-browser usage of the JavaScript Fullscreen API

Overview

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API, which lets you bring the page or any element into fullscreen. Smoothens out the browser implementation differences, so you don't have to.

This package is ESM. Please familiarize yourself with what that implies.
If you cannot use ESM or need to support older browsers without using transpilation, use version 5.2.0.

Not supported on iPhone

This package is feature complete. No new features will be accepted.

Demo

Install

Only 0.7 kB gzipped.

npm install screenfull

Also available on cdnjs (older version).

Why?

Screenfull

import screenfull from 'screenfull';

if (screenfull.isEnabled) {
	screenfull.request();
}

Vanilla JavaScript

document.fullscreenEnabled =
	document.fullscreenEnabled ||
	document.mozFullScreenEnabled ||
	document.documentElement.webkitRequestFullScreen;

function requestFullscreen(element) {
	if (element.requestFullscreen) {
		element.requestFullscreen();
	} else if (element.mozRequestFullScreen) {
		element.mozRequestFullScreen();
	} else if (element.webkitRequestFullScreen) {
		element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
	}
}

if (document.fullscreenEnabled) {
	requestFullscreen(document.documentElement);
}

// This is not even entirely comprehensive. There's more.

Support

Supported browsers

Note: Safari is supported on desktop and iPad, but not on iPhone. This is a limitation in the browser, not in Screenfull.

Documentation

Examples

Fullscreen the page

import screenfull from 'screenfull';

document.getElementById('button').addEventListener('click', () => {
	if (screenfull.isEnabled) {
		screenfull.request();
	} else {
		// Ignore or do something else
	}
});

Fullscreen an element

import screenfull from 'screenfull';

const element = document.getElementById('target');

document.getElementById('button').addEventListener('click', () => {
	if (screenfull.isEnabled) {
		screenfull.request(element);
	}
});

Hide navigation user-interface on mobile devices

import screenfull from 'screenfull';

const element = document.getElementById('target');

document.getElementById('button').addEventListener('click', () => {
	if (screenfull.isEnabled) {
		screenfull.request(element, {navigationUI: 'hide'});
	}
});

Fullscreen an element with jQuery

import screenfull from 'screenfull';

const element = $('#target')[0]; // Get DOM element from jQuery collection

$('#button').on('click', () => {
	if (screenfull.isEnabled) {
		screenfull.request(element);
	}
});

Toggle fullscreen on a image with jQuery

import screenfull from 'screenfull';

$('img').on('click', event => {
	if (screenfull.isEnabled) {
		screenfull.toggle(event.target);
	}
});

Detect fullscreen change

import screenfull from 'screenfull';

if (screenfull.isEnabled) {
	screenfull.on('change', () => {
		console.log('Am I fullscreen?', screenfull.isFullscreen ? 'Yes' : 'No');
	});
}

Remove listeners with:

import screenfull from 'screenfull';

screenfull.off('change', callback);

Detect fullscreen error

import screenfull from 'screenfull';

if (screenfull.isEnabled) {
	screenfull.on('error', event => {
		console.error('Failed to enable fullscreen', event);
	});
}

See the demo for more examples, and view the source.

Fullscreen an element with Angular.js

You can use the Angular.js binding to do something like:

<div ngsf-fullscreen>
	<p>This is a fullscreen element</p>
	<button ngsf-toggle-fullscreen>Toggle fullscreen</button>
</div>

Fullscreen the page with Angular 2

import {Directive, HostListener} from '@angular/core';
import screenfull from 'screenfull';

@Directive({
	selector: '[toggleFullscreen]'
})
export class ToggleFullscreenDirective {
	@HostListener('click') onClick() {
		if (screenfull.isEnabled) {
			screenfull.toggle();
		}
	}
}
<button toggleFullscreen>Toggle fullscreen<button>

API

.request(element, options?)

Make an element fullscreen.

Accepts a DOM element and FullscreenOptions.

The default element is <html>. If called with another element than the currently active, it will switch to that if it's a descendant.

If your page is inside an <iframe> you will need to add a allowfullscreen attribute (+ webkitallowfullscreen and mozallowfullscreen).

Keep in mind that the browser will only enter fullscreen when initiated by user events like click, touch, key.

Returns a promise that resolves after the element enters fullscreen.

.exit()

Brings you out of fullscreen.

Returns a promise that resolves after the element exits fullscreen.

.toggle(element, options?)

Requests fullscreen if not active, otherwise exits.

Accepts a DOM element and FullscreenOptions.

Returns a promise that resolves after the element enters/exits fullscreen.

.on(event, function)

Events: 'change' | 'error'

Add a listener for when the browser switches in and out of fullscreen or when there is an error.

.off(event, function)

Remove a previously registered event listener.

.onchange(function)

Alias for .on('change', function)

.onerror(function)

Alias for .on('error', function)

.isFullscreen

Returns a boolean whether fullscreen is active.

.element

Returns the element currently in fullscreen, otherwise undefined.

.isEnabled

Returns a boolean whether you are allowed to enter fullscreen. If your page is inside an <iframe> you will need to add a allowfullscreen attribute (+ webkitallowfullscreen and mozallowfullscreen).

.raw

Exposes the raw properties (prefixed if needed) used internally: requestFullscreen, exitFullscreen, fullscreenElement, fullscreenEnabled, fullscreenchange, fullscreenerror

FAQ

How can I navigate to a new page when fullscreen?

That's not supported by browsers for security reasons. There is, however, a dirty workaround. Create a seamless iframe that fills the screen and navigate to the page in that instead.

import screenfull from 'screenfull';

document.querySelector('#new-page-button').addEventListener(() => {
	const iframe = document.createElement('iframe')

	iframe.setAttribute('id', 'external-iframe');
	iframe.setAttribute('src', 'https://new-page-website.com');
	iframe.setAttribute('frameborder', 'no');
	iframe.style.position = 'absolute';
	iframe.style.top = '0';
	iframe.style.right = '0';
	iframe.style.bottom = '0';
	iframe.style.left = '0';
	iframe.style.width = '100%';
	iframe.style.height = '100%';

	document.body.prepend(iframe);
	document.body.style.overflow = 'hidden';
});

Resources

Comments
  • ScreenFull not working in iOS Chrome

    ScreenFull not working in iOS Chrome

    Whenever I try to open my application in fullscreen it shows following error in console.

    TypeError: undefined is not an object (evaluating 'screenfull__WEBPACK_IMPORTED_MODULE_23__["raw"].fullscreenchange')

    Now I know it does not work with safari on iPhone but It should work on Chrome and I am testing it in chrome.

    In the following condition,

    if (screenfull.enabled) {} => console.log(screenfull) => true //it should return an object This is the line where it is getting failed.

    opened by adnanrafique 23
  • Typescript Definitions: Property does not exist on type 'false | Screenfull'.

    Typescript Definitions: Property does not exist on type 'false | Screenfull'.

    Trying to access a property screenfull.isFullscreen is leading to this message:

    Property 'isFullscreen' does not exist on type 'false | Screenfull'. Property 'isFullscreen' does not exist on type 'false'.

    Import statement: import * as screenfull from "screenfull";

    Changing the definitions from declare const screenfull: Screenfull | false; to declare const screenfull: Screenfull; works.

    opened by Knacktus 11
  • Bug: typescript declaration

    Bug: typescript declaration

    Why are you using ScreenFull | { isEnabled: false}, it's causing issues.

    E.g: below is a direct copy from d.tsfile:

        if (screenfull.isEnabled) {
          screenfull.on('change', () => {
            console.log('Am I fullscreen?', screenfull.isFullscreen ? 'Yes' : 'No');
          });
        }
    

    and will throw an error:

    Property 'isFullscreen' does not exist on type 'Screenfull | { isEnabled: false; }'.
      Property 'isFullscreen' does not exist on type '{ isEnabled: false; }'.
    

    This means either I checked screenfull.isEnabled every time I access it

        if (screenfull.isEnabled) {
          screenfull.on('change', () => {
            console.log('Am I fullscreen?', screenfull.isEnabled && screenfull.isFullscreen ? 'Yes' : 'No');
          });
        }
    

    or I cast it every time:

        if (screenfull.isEnabled) {
          screenfull.on('change', () => {
            console.log('Am I fullscreen?', (screenfull as ScreenFull).isFullscreen ? 'Yes' : 'No');
          });
        }
    
        if (screenfull.isEnabled) {
          screenfull.on('change', () => {
            // will throw an error if I am in a strict env with `noImplitAny: true`.
            console.log('Am I fullscreen?', (screenfull as any).isFullscreen ? 'Yes' : 'No');
          });
        }
    

    Above error will appear in every method of screenfull.

    You may write this to force the users to check isEnabled first, but we have to check it again in every method of screenfull. Please consider changing the ScreenFull | { isEnabled: false}, as the type declaration now is really annoying.

    opened by Mister-Hope 10
  • Fix for non-browser environments

    Fix for non-browser environments

    Hi, this fixes a bug where document is undefined in non-browser environment.

    I saw https://github.com/sindresorhus/screenfull.js/commit/aacee479770a8cdb77dc158609961434ad258995 but needed this extra check as well.

    opened by oskarrough 9
  • Return a promise from `.request()`, `.exit()`, and `.toggle()`

    Return a promise from `.request()`, `.exit()`, and `.toggle()`

    Callbacks for basic methods

    Hey hey, was playing with your awesome library recently and it was really helpful, thank for the amazing work!

    However I found that sometimes it could be handy to have a callback functions for main methods - screenfull.request and screenfull.exit.

    Let's say if you want to do something like:

    screenfull.request(function () { // do something after browser entered full screen mode })
    

    Currently you can do that with event listeners but for a simple callback it seems like an overkill amount of work so I added a bit of callback functionality for request and exit methods. Maybe you'll find it helpful.

    P.S. It would be event better with Promises but since it's a really tiny library I decided not to pollute it with Promise polyfill

    opened by SidKH 8
  • on firefox exits fullscreen when a link is clicked

    on firefox exits fullscreen when a link is clicked

    I'm using firefox 14.0.1 on my fedora linux box. When i click on a link in my fullscreen page, it exits fullscreen, doesn't mantain the state of fullscreen during requests. This does not happen on chrome. For instance, on your demo page, if I click the Fullscreen Api link, fullscreen exits.

    opened by titomiguelcosta 8
  • You may need an appropriate loader to handle this file type

    You may need an appropriate loader to handle this file type

    Hi, I meet below problem when using your project:

    The steps are as follows: npm install screenfull

    import screenfull from 'screenfull'

    And then I got an error image

    I wonder what the reason is

    opened by AK47-dadada 6
  • Docs: could we clarify iphone/safari support

    Docs: could we clarify iphone/safari support

    Hello,

    In the readme there are sentences like:

    // Actually it's more if you want it to work in Safari, but let's not go there...
    

    and

    iPhone is not supported.
    

    This is a bit cryptic to me because it's the first time I have to do something related to fullscreen and I don't have the full picture in mind, to understand the meaning of these. (I just know that Apple is a big pain in the *** for many things related to Safari)

    From the first sentence, does it mean that "we can" or "we can not" make it work in safari? Does screenful.js work with Safari? (all versions?)

    For iPhone is not supported: iPhone is a device, so my question is: that's the whole Apple iOS system that is not supported or just Safari on an iPhone, or any browser in an iPhone?

    opened by AoDev 5
  • Deprecate onchange/onerror?

    Deprecate onchange/onerror?

    Initially had an idea to add an unbind method to remove all event handlers that screenfull creates and send a patch, but would much rather just clean up my own events that I registered through addEventListener. Would be happy to submit a patch removing these handlers if you're OK with it. :+1:

    opened by ben-eb 5
  • It exits with a new request?

    It exits with a new request?

    Hi guys. I have a button that in which I attach the event for the click to go fullscreen. I can enter fullscreen mode but then as soon as I click on something, the fullscreen is exit. Is it its normal behavior or I am doing something wrong? At least the exit button works here.

    The other possibility I am doing is to also attach a callback to such button (this is what I actually need) that does some code in the server. Doing this, I can remain in the full screen mode and I am not kicked out. However...if I try to exit full screen mode from the button, it does nothing. screenfull.isFullscreen answers false.

    So..I wonder, what should I do to be able to remain in fullscreen mode even with new requests and to also have a working exit button?

    Thanks!

    opened by marianopeck 5
  • Is it necessary to provide a UMD format entry file by default?

    Is it necessary to provide a UMD format entry file by default?

    As I import screenfull in a react project, the project will crash as webpack cannot import screenfull properly. I find the latest version
    provide a esm file. If I import screenfull from node_modules it won't be transpiled by babel by default. The error is as follows: image

    A possible solution is to include screenfull in webpack config so as to be transpiled by babel-loader.

    As a convention a package used in browser exposes a umd format file as a entry, to name a few, style-components,ant-design. So I would recommend provide a umd format rather than esm by default.

    opened by AlexRen94 4
  • [Bug] isEnabled always return true even full screen is disable by modify regedit for chrome

    [Bug] isEnabled always return true even full screen is disable by modify regedit for chrome

    User can Permanently Disable Chrome Full-Screen Mode. see https://geekermag.com/permanently-disable-full-screen-mode-chrome/

    After disable full screen mode, screenfull.isEnabled always return true, and screenfull.toggle also has problems.

    opened by wangzhengbo 0
  • Possibility of using css selector display-mode: fullscreen for more accurate `isFullscreen`

    Possibility of using css selector display-mode: fullscreen for more accurate `isFullscreen`

    Hi, I recently stumbled upon the relatively new display-mode: fullscreen css selector and it seems to work very nicely, accurately describing the fullscreen state even when the fullscreen isn't initiated by the current document's scripts (which doesn't work at the moment) - e.g. user presses f11 or document is iframed and externally fullscreened.

    Example:

    let matchedFullscreenMedia = window.matchMedia('(display-mode: fullscreen)').matches
    window.matchMedia('(display-mode: fullscreen)').addEventListener('change', ({ matches }) => {
      matchedFullscreenMedia = matches
    });
    

    I've tested in chrome and it works when the user presses f11 or the document is iframed+externally fullscreened and it seems to be well supported (https://caniuse.com/?search=display-mode)

    I'm wondering if there are any pitfalls in using this?

    opened by MCArth 0
  • Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.

    Failed to execute 'requestFullscreen' on 'Element': API can only be initiated by a user gesture.

    Every time you click, Report an error in vue3 + element plus

    <template>
      <el-tooltip v-model="visible" :hide-after="0">
        <template #content>
          <span>{{ toolTipContent }}</span>
        </template>
        <v-svg-icon
          :icon-class="iconClass"
          @click="handleToggle"
          @mouseenter="visible = true"
          @mouseleave="visible = false"
        />
      </el-tooltip>
    </template>
    
    <script setup lang="ts">
    import { ref, computed, onBeforeUnmount, onMounted } from 'vue'
    import { ElMessage } from 'element-plus'
    import screenfull from 'screenfull'
    
    const visible = ref(false)
    const isFullscreen = ref(false)
    const toolTipContent = computed(() => (isFullscreen.value ? '退出全屏' : '全屏'))
    const iconClass = computed(() => (isFullscreen.value ? 'exit-fullscreen' : 'fullscreen'))
    
    const handleToggle = () => {
      if (!screenfull.isEnabled) {
        ElMessage({
          message: 'you browser can not work',
          type: 'warning',
        })
        return false
      }
      screenfull.toggle().catch(() => '')
    }
    const handleChange = () => {
      isFullscreen.value = screenfull.isFullscreen
    }
    
    onBeforeUnmount(() => {
      if (screenfull.isEnabled) {
        screenfull.off('change', handleChange)
      }
    })
    
    onMounted(() => {
      if (screenfull.isEnabled) {
        screenfull.on('change', handleChange)
      }
    })
    </script>
    
    opened by Mr-Super-X 0
  • FullScreen mode goes to black after rotating the mobile device

    FullScreen mode goes to black after rotating the mobile device

    @sindresorhus It seems like whenever I rotating the chrome for Android during FullScreen mode, and exit fullScreen mode and back to fullScreen mode again.It will goes to complete black....and it only happens on chrome, Firefox is okay So can anyone tell me how to fix this issue? I have been search the solution almost three days, beginning to this is the just bug of google chrome.

    Here is the code I wrote :

    image

    opened by dracarys55 2
Releases(v6.0.2)
  • v6.0.2(Jun 19, 2022)

  • v6.0.1(Jan 16, 2022)

  • v6.0.0(Nov 3, 2021)

    Breaking

    • This package is now pure ESM. Please read this.
      • If you cannot easily move to ESM. Just stay on version 5.2.0. It's stable and fine.
    • This package now uses modern JavaScript syntax. If you need support for older browsers, you need to transpile the code with Babel.
    • A minified version is no longer provided in the package. It's better to minify your project as a whole in your own build step.
    • screenfull.element is now undefined instead of null when there's no fullscreen element.
    • The document global is no longer polyfilled. If you run this package in a non-browser environment, it's up to you to polyfill required browser globals.

    https://github.com/sindresorhus/screenfull.js/compare/v5.2.0...v6.0.0

    Source code(tar.gz)
    Source code(zip)
  • v5.2.0(Nov 3, 2021)

  • v5.1.0(Dec 24, 2020)

  • v5.0.2(Feb 13, 2020)

    • Return the native promise when it exists https://github.com/sindresorhus/screenfull.js/commit/536595d5d88e10d5ee9df13d477488f3637171fd

    https://github.com/sindresorhus/screenfull.js/compare/v5.0.1...v5.0.2

    Source code(tar.gz)
    Source code(zip)
  • v5.0.1(Jan 19, 2020)

    • Fix type definition https://github.com/sindresorhus/screenfull.js/commit/f0a14a30e26ccef536bc6ba1a5c35e304dd434ac

    https://github.com/sindresorhus/screenfull.js/compare/v5.0.0...v5.0.1

    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Sep 9, 2019)

    Breaking

    • Rename screenfull.enabled to screenfull.isEnabled 9b98fcc
    • Drop Safari 5.1 (it's ancient) workaround 927e361
    • Unify checking for fullscreen availability (#154) 633ea78 Previously, you had to check if (screenfull && screenfull.enabled) {} before using it. Now you just use if (screenfull.isEnabled) {}.

    Breaking for TypeScript users

    • Require Screenfull to be imported using require when using TypeScript 2664e56 You need to change import screenfull from 'screenfull'; to import screenfull = require('screenfull');

    https://github.com/sindresorhus/screenfull.js/compare/v4.2.1...v5.0.0

    Source code(tar.gz)
    Source code(zip)
  • v4.2.1(Jul 27, 2019)

  • v4.2.0(Mar 31, 2019)

  • v4.1.0(Mar 19, 2019)

  • v4.0.1(Feb 18, 2019)

  • v4.0.0(Dec 15, 2018)

    Breaking:

    • Return a promise from .request(), .exit(), and .toggle(). That means that this package now requires Promise or a promise polyfill. cd8afd9
    Source code(tar.gz)
    Source code(zip)
  • v3.3.0(Jul 6, 2017)

  • v3.2.0(Apr 16, 2017)

    Screenfull gracefully handles non-browser JS environments. https://github.com/sindresorhus/screenfull.js/commit/aacee479770a8cdb77dc158609961434ad258995

    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(Mar 13, 2017)

  • v3.0.0(Nov 24, 2015)

  • v2.0.0(Dec 23, 2014)

    Remove deprecated .onchange() and .onerror() methods. Replacement: https://github.com/sindresorhus/screenfull.js#detect-fullscreen-change

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Sep 6, 2013)

Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns.
Sindre Sorhus
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A fullscreen scroll-based slideshow with a content view powered by GreenSock's Observer plugin.

Fullscreen Scrolling Slideshow A fullscreen scroll-based slideshow with a content view powered by GreenSock's Observer plugin. Article on Codrops Demo

Codrops 84 Jan 3, 2023
Sample project to demonstrate Playwright Test usage, pointing to ServeRest API and Front-end

demo-playwright-test This is a sample project to demonstrate Playwright Test usage, running tests against ServeRest API and Front-end. Pre-requisites

Stefan Teixeira 30 Oct 24, 2022
Modern Cross Browser Testing in JavaScript using Playwright

Modern Cross Browser Testing in JavaScript using Playwright This repository contains the example code for the Modern Cross Browser Testing in JavaScri

Applitools 5 Oct 3, 2022
A lightweight cross browser javascript scrollbar.

tinyscrollbar ** HELP MAINTAINER NEEDED!! ** Environments in which to use tinyscrollbar Browser support differs between the jQuery plugin and the plai

Maarten Baijs 398 Nov 9, 2022
🔨 Cross-browser JavaScript library to disable scrolling page

scroll-lock Cross-browser JavaScript library to disable scrolling page Live demo | README на русском New features 2.0 More advanced touch event handli

null 253 Dec 17, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
This is a project being built to show the usage of Webpack. It's an application were you are able to add a task to the list, and remove a task from the list

Microverse Project To Do List This is a project being built to show the usage of webpack. Its an application were you are able to add a task to the li

Roland Ossisa Yuma 4 May 6, 2022
Usage Heatmap for Shiny with heatmap.js

shinyHeatmap The goal of {shinyHeatmap} is to provide a free and local alternative to more advanced user tracking platform such as Hotjar. {shinyHeatm

RinteRface 15 Dec 21, 2022
💪 Reserve machine/rack/bench usage at a gym to minimize waiting times.

Gym Reservation App ?? Oscar Su, Amelia Reeves, Nathan Ma Possible name: Pump Program The goal is to reduce/eliminate the time spent waiting on others

Oscar Su 4 Jul 8, 2022
This is a demo project for the SecTester JS SDK framework, with some installation and usage examples

SecTester SDK Demo Table of contents About this project About SecTester Setup Fork and clone this repo Get a Bright API key Explore the demo applicati

NeuraLegion 15 Dec 16, 2022
A script that combines a folder of SVG files into a single sprites file and generates type definitions for safe usage.

remix-sprites-example A script that combines a folder of .svg files into a single sprites.svg file and type definitions for safe usage. Technical Over

Nicolas Kleiderer 19 Nov 9, 2022
Plugins for my daily usage.

Joplin Plugin Bundle Plugins in one panel. Some of the plugins come from other repo, and I modified them to show all the plugin panels in the same pan

null 20 Dec 24, 2022
Mongo Strict is a TypeScript based smart MongoDB ORM, It makes the usage of MongoDB safer, easier and faster with a better performance...

mongo-strict mongo-strict is compatible with mongo >= 5 Mongo Strict is a TypeScript-based smart MongoDB ORM, It makes the usage of MongoDB safer, eas

Mohamed Kamel 4 Sep 22, 2022
The classical game of Liar's Dice enhanced with the usage of Zero-Knowledge Proof

Liar's Dice An online multiplayer game showcasing the potential of Aleo's Zero Knowledge Proof platform. Local deployment Prerequisites Setup dnsmasq

Kryha 4 Dec 15, 2022
The classical game of Liar's Dice enhanced with the usage of Zero-Knowledge Proof

Liar's Dice An online multiplayer game showcasing the potential of Aleo's Zero Knowledge Proof platform. Local deployment Prerequisites Setup dnsmasq

Kryha 3 Oct 20, 2022
An open source API wrapper for TechHost API.

TechHost API Wrapper An open source API wrapper for TechHost API. Badges Installation Install techhost-api-wrapper with npm. npm install techhost-api-

Eight∞ 4 Jun 23, 2022
News API Wrapper for Violetics API News

News API Wrapper for Violetics API News

Violetics 3 Mar 23, 2022