LoginSignup
32
33

More than 5 years have passed since last update.

ブラウザでファイルダウンロードが終わったタイミングでJSでなにかする方法

Posted at

この投稿の参考元

こちらの記事を参考にさせてもらいました
http://d.hatena.ne.jp/nabehiro/20140208/1391850498 

概要

何かしらのファイルダウンロードが終わった時(html以外のレスポンスを受け取るようなとき)に、受け取り終わった後何かやりたいというケースについて。(意外と業務システム屋だと多い気がする)
この動きを必要とした時に、参考元のブログの方法がだいぶ理想的な動きだったので、自分用に修正を加えたものをメモ。

サーバーサイド

今回はPHPで。

// 名前・値・有効期限・パス
setcookie('downloaded','complete',0,'/');

クライアントサイド


$(function(){
        // フォームがサブミットされた時
    $('#your_form').submit(function() {
        var onComplete = function(){
            if (getCookieValue('downloaded') == 'complete') {
                // 任意の処理
            }
            else{
                // 再起してCookieが作成されたか監視
                setTimeout(onComplete, 1000);
            }
        }
        onComplete();
    });
        // クッキー値取得
    function getCookieValue(name){
        var result = '',
            key = name+'=',
            _cookie = document.cookie,
            _s = _cookie.indexOf(key),
            _e = _cookie.indexOf(';',_s);

        _e = _e === -1 ? _cookie.length : _e;
        result = decodeURIComponent(_cookie.substring(_s,_e)).replace(key,'');
        return result;
    }
        // クッキー消す
    function deleteCookie(name){
        document.cookie = name+'=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
    }
});

メモ

Cookie消すときはpath指定してないと消えないので注意

32
33
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
33