search
HomeWeb Front-endJS TutorialDetailed explanation of JS full screen and exit full screen (including code)

We may see a lot of exiting full-screen effects and full-screen effects when watching video websites. Here we will introduce you to the use of js full-screen and exit full-screen code examples. Friends who need it can refer to it

JS full screen and exit full screen

js implements the functions of browser window full screen and exit full screen. Mainstream browsers on the market such as: Google, Firefox, 360, etc. are all compatible, but the lower version of IE is a bit Flaws (there is still a status bar at the bottom in full screen mode).

This demo is basically enough. Just copy the source code below and save it as an html file to see the effect.

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js全屏和退出全屏代码</title>
<body>
<!-- requestFullScreen(document.documentElement): 整个网页进入全屏
  requestFullScreen(document.getElementById("video-box")): 指定某块区域全屏
 -->
<button onclick="requestFullScreen(document.documentElement)">全屏显示</button>
<button onclick="exitFull()">退出全屏</button>
</body>
<script type="text/javascript">
function requestFullScreen(element) {
 // 判断各种浏览器,找到正确的方法
 var requestMethod = element.requestFullScreen || //W3C
 element.webkitRequestFullScreen || //Chrome等
 element.mozRequestFullScreen || //FireFox
 element.msRequestFullScreen; //IE11
 if (requestMethod) {
  requestMethod.call(element);
 }
 else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
  var wscript = new ActiveXObject("WScript.Shell");
  if (wscript !== null) {
   wscript.SendKeys("{F11}");
  }
 }
}

//Exit full screen to determine browser type

function exitFull() {
 // 判断各种浏览器,找到正确的方法
 var exitMethod = document.exitFullscreen || //W3C
 document.mozCancelFullScreen || //Chrome等
 document.webkitExitFullscreen || //FireFox
 document.webkitExitFullscreen; //IE11
 if (exitMethod) {
  exitMethod.call(document);
 }
 else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
  var wscript = new ActiveXObject("WScript.Shell");
  if (wscript !== null) {
   wscript.SendKeys("{F11}");
  }
 }
}
</script>
</html>

We know, browse To go full screen, usually press the shortcut key F11. It is not uncommon for JS to control the browser's full screen. It makes web applications look more like native software applications. For example, ordering system, calling system, etc.

There are many JS methods to make the browser full screen and exit full screen. This is not the point. The point is to note: browser full screen can only be triggered by mouse gesture click events.

JS full screen method

var $fullScreen = document.getElementById("js-fullScreen");//按钮 
if ($fullScreen) { 
  $fullScreen.addEventListener("click", function () { 
    var docElm = document.documentElement; 
    if (docElm.requestFullscreen) { 
      docElm.requestFullscreen(); 
    } 
    else if (docElm.msRequestFullscreen) { 
      docElm.msRequestFullscreen(); 
    } 
    else if (docElm.mozRequestFullScreen) { 
      docElm.mozRequestFullScreen(); 
    } 
    else if (docElm.webkitRequestFullScreen) { 
      docElm.webkitRequestFullScreen(); 
    } 
  }, false); 
}

JS exit full screen method

var $cancelFullScreen = document.getElementById("js-cancelFullScreen"); 
if ($cancelFullScreen) { 
  $cancelFullScreen.addEventListener("click", function () { 
    if (document.exitFullscreen) { 
      document.exitFullscreen(); 
    } 
    else if (document.msExitFullscreen) { 
      document.msExitFullscreen(); 
    } 
    else if (document.mozCancelFullScreen) { 
      document.mozCancelFullScreen(); 
    } 
    else if (document.webkitCancelFullScreen) { 
      document.webkitCancelFullScreen(); 
    } 
  }, false); 
}

Console warning

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

Interpretation: on "Element" Execution of the "requestFullscreen" method failed, the javascript API only allows creation through gestures! (i.e. no permission)

Usually caused by the programmer wanting to trigger the browser to automatically display full screen. But I'm sorry, this method doesn't work. It must be created through gestures. Even onload, trigger(), and mouseover cannot be triggered!

Official explanation

The Element.requestFullscreen() method issues an asynchronous request to display the element in full screen. But there is no guarantee that the element will be put into full screen mode.

If full screen mode is allowed, the document will receive a fullscreenchange event to let it know that it is now in full screen mode. If permission is denied, the document receives a FullScreenError event.

Conclusion

Maybe for the sake of user experience, client-side javascript allows the browser to be full-screen only through mouse gesture click events, that is, click() .

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Nodejs Electron ubuntu installation steps detailed explanation

Native JS AJAX Produce three-level linkage effect (with code)

Vue.jsTwo-way binding implementation step instructions

The above is the detailed content of Detailed explanation of JS full screen and exit full screen (including code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function