是否可以使用javascript捕获浏览器的文件打开/保存对话框事件

laz*_*tor 17 javascript browser jquery dom-events

使用javascript可以监听浏览器的文件打开/保存对话框事件.当我收到通知现在已打开保存文件对话框时,我想执行操作.具体来说,我想在对话框打开时隐藏加载微调器(但这很可能是任何其他操作)

我相信我可以为我创建的对话框执行此操作,不确定是否可以对浏览器的标准对话框执行此操作.

任何指针都非常有用.

Bro*_*ams 13

是! 您可以利用大多数浏览器(在Chrome,Firefox和IE上测试好)beforeunload在单个文件下载对话框打开之前触发事件.

所以像这样的代码将起作用:

$(window).bind ("beforeunload",  function (zEvent) {
    // PERFORM DESIRED ACTIONS HERE.
    /* This code will fire just before the Individual-file Download 
       dialog opens.
       Note that it will also fire before the tab or window is closed, 
       but that should not be a problem for this application.
    */
} );
Run Code Online (Sandbox Code Playgroud)


打开并运行此代码段以查看其效果:

$(window).bind ("beforeunload",  function (zEvent) {
    $("#dwnldStatus").text ("This code runs just before the file open/save dialog pops up.");
} );

$("#directDwnload").click ( function () {
    fireDownload ();
} );

$("#ResetTimer").click ( function () {
    $("#dwnldStatus").html (
        'Download will start in <span id="timeleft">3</span> seconds.'
    );
    fireTimer (3);
} );

function fireDownload () {
    window.location.assign (
        "//phs.googlecode.com/files/Download%20File%20Test.zip"
    );
}

function fireTimer (secondsLeft) {
    this.secondsLeft    = secondsLeft || 30;
    this.countdownTimer = this.countdownTimer || null;

    if ( ! this.countdownTimer) {
        this.countdownTimer = setInterval ( function() {
                this.secondsLeft--;
                $("#timeleft").text (this.secondsLeft);
                if (this.secondsLeft <= 0) {
                    clearInterval (this.countdownTimer);
                    this.countdownTimer = null;
                    fireDownload ();
                }
            },
            1000
        );
    }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>Activate one of the download buttons.  The timer button is just like any other javascript initiated download, no additional  click is needed.</p>
<p>The javascript detects when the File/Save dialog pops up and changes the status to "This code runs just before the file open/save dialog pops up.".</p>
<p>Note that it is not necessary to download the file. You can cancel the download.</p>

<div id="dwnldStatus"></div>
<button id="ResetTimer">Set timer to 3 seconds.</button>
<button id="directDwnload">Download the file now.</button>
Run Code Online (Sandbox Code Playgroud)


请注意,beforeunload在关闭选项卡或窗口之前也会触发,因此请进行相应的计划.对于这个问题,这应该不是问题.


Mat*_*hen 9

不,没有事件发生.

  • 为什么放松?我会说保护用户隐私是一件非常好的事情.顺便说一下+1. (2认同)