Подтвердить что ты не робот

Можно ли перехватить событие открытия файла в браузере, используя Javascript?

Используя Javascript, можно прослушивать события диалогового окна открытия/сохранения файла браузера. Я хочу выполнить действие, когда я получаю уведомление о том, что теперь открыто диалоговое окно сохранения файла. В частности, я хочу скрыть загрузчик, когда открывается диалоговое окно (но это вполне может быть любое другое действие)

Я полагаю, что могу сделать это для диалогового окна, которое я создаю, но не уверен, что это можно сделать для стандартного диалогового окна браузера.

Любые указатели на это были бы очень полезны.

4b9b3361

Ответ 1

Нет, для этого события нет.

Ответ 2

Да! Вы можете воспользоваться тем, что большинство браузеров (протестировано в 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.
    */
} );


Откройте и запустите этот фрагмент, чтобы увидеть его в действии:

$(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
        );
    }
}
<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>

Ответ 3

Смотрите все элементы, которые могут вызывать диалог с файлом.

Например, обрабатывайте события щелчка на элементах <input type="file" />. что-то вроде:

$('input:file').click(function(){ // onclick of file input
    $('.spinner').hide(); // hide spinner
});