Javascript(无 jQuery) - Google Chrome 有时会错误地检测窗口宽度

标签 javascript google-chrome browser width detect

注意:这将作为错误报告给 Google,但修复通常会延迟。

基于窗口宽度调用函数的网页在 IE、Firefox 等中可以正常工作,但在 Chrome 中“有时”会失败。仅当目标网页在浏览器启动时自动重新加载时,才会出现该问题(在基于 Chromium 的浏览器中)。

<script>

var dde = document.documentElement;

if(!document.documentElement) dde = document.body; // fix for IE6 and earlier 

myWidth = Math.max(dde.scrollWidth,dde.offsetWidth,dde.clientWidth);

if(myWidth < 960) document.location.href="http://www.gooplusplus.com/mini.php";  

</script>

最佳答案

进一步测试发现,在浏览器启动时,Chrome 会根据非最大化窗口大小获取窗口宽度结果,即使窗口实际上已最大化。此外,此错误仅发生在非事件浏览器选项卡上。

找到解决方案所需的两个步骤是检测:

(1) 浏览器是基于 Chromium 的吗? --> navigator.userAgent.indexOf("Chrome/")>0

(2) 该选项卡是否处于非事件状态? --> document.webkitVisibilityState == "隐藏"

测试网址:http://www.gooplusplus.com/chrome-bug.html

我的部分解决方案:

<script>

var dde = document.documentElement;

var tabVisible = document.webkitVisibilityState;

if(!document.documentElement) dde = document.body; // fix for IE6 and earlier 

myWidth = Math.max(dde.scrollWidth,dde.offsetWidth,dde.clientWidth);

if( ( navigator.userAgent.indexOf("Chrome/")<0 || tabVisible!="hidden" ) && myWidth < 960 ) 
    document.location.href="http://www.gooplusplus.com/mini.php";  

</script>

这就是我的基于窗口宽度的 URL 重定向所需的全部内容。然而,这绕过了另一个假设的情况,其中 (1) 浏览器是 Chrome,(2) 选项卡处于非事件状态(隐藏),但是 (3) 最大尺寸确实 < 960 像素。那么,有没有更完整的解决方案呢?

关于Javascript(无 jQuery) - Google Chrome 有时会错误地检测窗口宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012945/

相关文章:

javascript - Sequelize 创建不是一个函数?

JavaScript Electron : how to increase performance and prevent crashes when working with big amounts of data

javascript - 如何使用 Protractor 获取新打开的选项卡 URL

html - 底部填充的存在/不存在会改变 Chrome 上的内框大小

Android 读取浏览器历史记录

javascript - 如果我用 fadeToggle 替换 fadeIn/fadeOut 为什么它不起作用

javascript - 无论格式如何都匹配电话号码

javascript - 为动态 url 设置 noopener

javascript - 在 HTML 中加载 Js 文件

html - 使用浏览器 Logo