V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
chenliangngng
V2EX  ›  程序员

js 如何捕获浏览器抛出的黄色警告异常?

  •  
  •   chenliangngng · 2019-10-04 21:08:19 +08:00 · 6289 次点击
    这是一个创建于 1637 天前的主题,其中的信息可能已经有所发展或是发生改变。

    源代码如下:

    html 部分:

    <button id="button1">延迟 4s</button><button id="button2">延迟 5s</button><input id="input" type="file">

    js 部分:

    document.getElementById('button1').onclick = function(){ setTimeout(() => { document.getElementById('input').click() }, 4000) }

    document.getElementById('button2').onclick = function(){ setTimeout(() => { document.getElementById('input').click() }, 5000) }

    点击 button1,延迟 4s,会弹出 input 弹窗;

    点击 button2,延迟 5s,弹窗将失效,控制台报黄色警告: File chooser dialog can only be shown with a user activation.

    搜相关资料是由于浏览器安全机制,如果距离用户操作时间较长的话,会导致此类事件失效。

    我尝试用 try catch 和 window.onerror,都无法捕获此异常,所以无法判断是不是出错了。

    不知道大佬们有啥高招?

    9 条回复    2019-10-06 19:14:42 +08:00
    oatw
        1
    oatw  
       2019-10-04 21:25:41 +08:00 via iPhone
    试试覆盖 console.warn 方法?
    nifury
        2
    nifury  
       2019-10-04 23:29:54 +08:00
    弹窗失效的话之前选择的文件会被清除的吧
    你只要监听 input 的 onchange 应该就能知道了
    chenliangngng
        3
    chenliangngng  
    OP
       2019-10-04 23:47:36 +08:00 via Android
    @oatw 黄色告警不是我写的,是 chrome 控制台弹出的,我写的代码除了 html body script 这些标签,上面的就是全部
    chenliangngng
        4
    chenliangngng  
    OP
       2019-10-04 23:49:13 +08:00 via Android
    @nifury 你尝试一下只点击 button2,选文件的弹窗是不会出来的,取而代之的是控制台报类似 console.warn 的信息
    nifury
        5
    nifury  
       2019-10-05 00:00:55 +08:00
    @chenliangngng #4 嗯……说的没错。这个乍一看似乎没有好的解决办法
    zqx
        6
    zqx  
       2019-10-05 06:27:32 +08:00 via Android
    这个要看浏览器有没有暴露 BOM 的方法了,不同的浏览器不一样
    azh7138m
        7
    azh7138m  
       2019-10-05 12:12:36 +08:00
    没有,这个是安全特性
    部分操作需要由用户行为触发
    myqoo
        8
    myqoo  
       2019-10-05 20:39:24 +08:00
    为什么要这样写?老版本的 Chrome 连 setTimeout 1ms 都不允许的,还是会有兼容性问题的
    chenliangngng
        9
    chenliangngng  
    OP
       2019-10-06 19:14:42 +08:00 via Android
    @myqoo 因为有业务需求导致要用其他方式触发 input,而中间有间隔,上例只是一个简单的 demo。我想要知道的是如何捕获这类问题,比如,用于异常场景时出现时,提示用户重试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3330 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 13:18 · PVG 21:18 · LAX 06:18 · JFK 09:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.