如何检测浏览器已进入全屏

How to detect browser has gone to full screen

本文关键字:浏览器 何检测 检测      更新时间:2023-09-26

TLDR;

我可以通过全屏API检测浏览器是否已进入全屏,但我无法通过f11或浏览器菜单(特别是chrome)检测浏览器是否进入全屏。

原件:

目前我正在使用screenfull进入全屏并检测浏览器是否处于全屏状态。问题是,当浏览器通过浏览器功能进入全屏(即f11或通过浏览器菜单进入全屏)时,我不想显示全屏切换按钮。这是因为javascript全屏API似乎无法检测到您处于全屏状态,也无法在您通过浏览器功能进入全屏状态时让您离开全屏。我只能检测f11是否被击中,但这在mac上或通过浏览器菜单启动全屏时都不起作用。

关于如何检测是否通过浏览器功能启动全屏,有什么想法吗?我只针对兼容webgl的浏览器,这样可以减少很多麻烦。

我还没有测试过它的可靠性,但这是我的选择。

  //without jQuery
window.addEventListener('resize', function(){
  if(screen.width === window.innerWidth){
   // this is full screen
  }
});

  //with jQuery
$(document).ready(function() {
  $(window).on('resize', function(){
    if(screen.width === window.innerWidth){
      // this is full screen
    }
  });
});

当按下F11按钮和其他方法时,这似乎有效,所以它应该能捕捉到全屏api没有的边缘情况。尽管我不确定screen.width与window.innerWidth的比较是否是检查全屏的可靠方法。也许其他人可以对此进行补充/批评。

使用fullscreenchange事件来检测全屏更改事件,或者如果您不想处理供应商前缀,您也可以监听resize事件(当进入或退出全屏时也会触发的窗口调整大小事件),然后检查document.fullscreenElement是否为空,以确定全屏模式是否打开。您需要相应地为fullscreenElement添加供应商前缀。我会用这样的东西:

var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement ||
document.webkitFullscreenElement || document.msFullscreenElement;

https://msdn.microsoft.com/en-us/library/dn312066aspx有一个很好的例子,我在下面引用。他们使用了fullscreenChange事件,但您可以监听"resize"事件

document.addEventListener("fullscreenChange", function () {
          if (fullscreenElement != null) {
              console.info("Went full screen");
          } else {
              console.info("Exited full screen");              
          }
      });

在不同的浏览器和设备上尝试了很多方法后,以下解决方案对我来说可靠。

 window.addEventListener("resize", () => {
        setTimeout(() => {
            const windowWidth = window.innerWidth * window.devicePixelRatio;
            const windowHeight = window.innerHeight * window.devicePixelRatio;
            const screenWidth = window.screen.width;
            const screenHeight = window.screen.height;
            console.log(windowWidth/screenWidth);
            console.log(windowHeight/screenHeight);
            if (((windowWidth/screenWidth)>=0.95) && ((windowHeight/screenHeight)>=0.95)) {
                console.log("Fullscreen");
            }
            else {
                console.log("Not Fullscreen");
            }
        }, 100);
    })